Edit on GitHub

Expressions

Every AST node in SQLGlot is represented by a subclass of Expression.

This module contains the implementation of all supported Expression types. Additionally, it exposes a number of helper functions, which are mainly used to programmatically build SQL expressions, such as sqlglot.expressions.select.


   1"""
   2## Expressions
   3
   4Every AST node in SQLGlot is represented by a subclass of `Expression`.
   5
   6This module contains the implementation of all supported `Expression` types. Additionally,
   7it exposes a number of helper functions, which are mainly used to programmatically build
   8SQL expressions, such as `sqlglot.expressions.select`.
   9
  10----
  11"""
  12
  13from __future__ import annotations
  14
  15import datetime
  16import math
  17import numbers
  18import re
  19import typing as t
  20from collections import deque
  21from copy import deepcopy
  22from enum import auto
  23
  24from sqlglot.errors import ParseError
  25from sqlglot.helper import (
  26    AutoName,
  27    camel_to_snake_case,
  28    ensure_collection,
  29    ensure_list,
  30    seq_get,
  31    split_num_words,
  32    subclasses,
  33)
  34from sqlglot.tokens import Token
  35
  36if t.TYPE_CHECKING:
  37    from sqlglot.dialects.dialect import DialectType
  38
  39E = t.TypeVar("E", bound="Expression")
  40
  41
  42class _Expression(type):
  43    def __new__(cls, clsname, bases, attrs):
  44        klass = super().__new__(cls, clsname, bases, attrs)
  45
  46        # When an Expression class is created, its key is automatically set to be
  47        # the lowercase version of the class' name.
  48        klass.key = clsname.lower()
  49
  50        # This is so that docstrings are not inherited in pdoc
  51        klass.__doc__ = klass.__doc__ or ""
  52
  53        return klass
  54
  55
  56class Expression(metaclass=_Expression):
  57    """
  58    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
  59    context, such as its child expressions, their names (arg keys), and whether a given child expression
  60    is optional or not.
  61
  62    Attributes:
  63        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
  64            and representing expressions as strings.
  65        arg_types: determines what arguments (child nodes) are supported by an expression. It
  66            maps arg keys to booleans that indicate whether the corresponding args are optional.
  67
  68    Example:
  69        >>> class Foo(Expression):
  70        ...     arg_types = {"this": True, "expression": False}
  71
  72        The above definition informs us that Foo is an Expression that requires an argument called
  73        "this" and may also optionally receive an argument called "expression".
  74
  75    Args:
  76        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
  77        parent: a reference to the parent expression (or None, in case of root expressions).
  78        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
  79            uses to refer to it.
  80        comments: a list of comments that are associated with a given expression. This is used in
  81            order to preserve comments when transpiling SQL code.
  82        _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
  83            optimizer, in order to enable some transformations that require type information.
  84    """
  85
  86    key = "expression"
  87    arg_types = {"this": True}
  88    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash")
  89
  90    def __init__(self, **args: t.Any):
  91        self.args: t.Dict[str, t.Any] = args
  92        self.parent: t.Optional[Expression] = None
  93        self.arg_key: t.Optional[str] = None
  94        self.comments: t.Optional[t.List[str]] = None
  95        self._type: t.Optional[DataType] = None
  96        self._meta: t.Optional[t.Dict[str, t.Any]] = None
  97        self._hash: t.Optional[int] = None
  98
  99        for arg_key, value in self.args.items():
 100            self._set_parent(arg_key, value)
 101
 102    def __eq__(self, other) -> bool:
 103        return type(self) is type(other) and hash(self) == hash(other)
 104
 105    @property
 106    def hashable_args(self) -> t.Any:
 107        args = (self.args.get(k) for k in self.arg_types)
 108
 109        return tuple(
 110            (tuple(_norm_arg(a) for a in arg) if arg else None)
 111            if type(arg) is list
 112            else (_norm_arg(arg) if arg is not None and arg is not False else None)
 113            for arg in args
 114        )
 115
 116    def __hash__(self) -> int:
 117        if self._hash is not None:
 118            return self._hash
 119
 120        return hash((self.__class__, self.hashable_args))
 121
 122    @property
 123    def this(self):
 124        """
 125        Retrieves the argument with key "this".
 126        """
 127        return self.args.get("this")
 128
 129    @property
 130    def expression(self):
 131        """
 132        Retrieves the argument with key "expression".
 133        """
 134        return self.args.get("expression")
 135
 136    @property
 137    def expressions(self):
 138        """
 139        Retrieves the argument with key "expressions".
 140        """
 141        return self.args.get("expressions") or []
 142
 143    def text(self, key) -> str:
 144        """
 145        Returns a textual representation of the argument corresponding to "key". This can only be used
 146        for args that are strings or leaf Expression instances, such as identifiers and literals.
 147        """
 148        field = self.args.get(key)
 149        if isinstance(field, str):
 150            return field
 151        if isinstance(field, (Identifier, Literal, Var)):
 152            return field.this
 153        if isinstance(field, (Star, Null)):
 154            return field.name
 155        return ""
 156
 157    @property
 158    def is_string(self) -> bool:
 159        """
 160        Checks whether a Literal expression is a string.
 161        """
 162        return isinstance(self, Literal) and self.args["is_string"]
 163
 164    @property
 165    def is_number(self) -> bool:
 166        """
 167        Checks whether a Literal expression is a number.
 168        """
 169        return isinstance(self, Literal) and not self.args["is_string"]
 170
 171    @property
 172    def is_int(self) -> bool:
 173        """
 174        Checks whether a Literal expression is an integer.
 175        """
 176        if self.is_number:
 177            try:
 178                int(self.name)
 179                return True
 180            except ValueError:
 181                pass
 182        return False
 183
 184    @property
 185    def is_star(self) -> bool:
 186        """Checks whether an expression is a star."""
 187        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
 188
 189    @property
 190    def alias(self) -> str:
 191        """
 192        Returns the alias of the expression, or an empty string if it's not aliased.
 193        """
 194        if isinstance(self.args.get("alias"), TableAlias):
 195            return self.args["alias"].name
 196        return self.text("alias")
 197
 198    @property
 199    def name(self) -> str:
 200        return self.text("this")
 201
 202    @property
 203    def alias_or_name(self):
 204        return self.alias or self.name
 205
 206    @property
 207    def output_name(self):
 208        """
 209        Name of the output column if this expression is a selection.
 210
 211        If the Expression has no output name, an empty string is returned.
 212
 213        Example:
 214            >>> from sqlglot import parse_one
 215            >>> parse_one("SELECT a").expressions[0].output_name
 216            'a'
 217            >>> parse_one("SELECT b AS c").expressions[0].output_name
 218            'c'
 219            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
 220            ''
 221        """
 222        return ""
 223
 224    @property
 225    def type(self) -> t.Optional[DataType]:
 226        return self._type
 227
 228    @type.setter
 229    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
 230        if dtype and not isinstance(dtype, DataType):
 231            dtype = DataType.build(dtype)
 232        self._type = dtype  # type: ignore
 233
 234    @property
 235    def meta(self) -> t.Dict[str, t.Any]:
 236        if self._meta is None:
 237            self._meta = {}
 238        return self._meta
 239
 240    def __deepcopy__(self, memo):
 241        copy = self.__class__(**deepcopy(self.args))
 242        if self.comments is not None:
 243            copy.comments = deepcopy(self.comments)
 244
 245        if self._type is not None:
 246            copy._type = self._type.copy()
 247
 248        if self._meta is not None:
 249            copy._meta = deepcopy(self._meta)
 250
 251        return copy
 252
 253    def copy(self):
 254        """
 255        Returns a deep copy of the expression.
 256        """
 257        new = deepcopy(self)
 258        new.parent = self.parent
 259        return new
 260
 261    def append(self, arg_key, value):
 262        """
 263        Appends value to arg_key if it's a list or sets it as a new list.
 264
 265        Args:
 266            arg_key (str): name of the list expression arg
 267            value (Any): value to append to the list
 268        """
 269        if not isinstance(self.args.get(arg_key), list):
 270            self.args[arg_key] = []
 271        self.args[arg_key].append(value)
 272        self._set_parent(arg_key, value)
 273
 274    def set(self, arg_key, value):
 275        """
 276        Sets `arg_key` to `value`.
 277
 278        Args:
 279            arg_key (str): name of the expression arg.
 280            value: value to set the arg to.
 281        """
 282        self.args[arg_key] = value
 283        self._set_parent(arg_key, value)
 284
 285    def _set_parent(self, arg_key, value):
 286        if hasattr(value, "parent"):
 287            value.parent = self
 288            value.arg_key = arg_key
 289        elif type(value) is list:
 290            for v in value:
 291                if hasattr(v, "parent"):
 292                    v.parent = self
 293                    v.arg_key = arg_key
 294
 295    @property
 296    def depth(self):
 297        """
 298        Returns the depth of this tree.
 299        """
 300        if self.parent:
 301            return self.parent.depth + 1
 302        return 0
 303
 304    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
 305        """Yields the key and expression for all arguments, exploding list args."""
 306        for k, vs in self.args.items():
 307            if type(vs) is list:
 308                for v in vs:
 309                    if hasattr(v, "parent"):
 310                        yield k, v
 311            else:
 312                if hasattr(vs, "parent"):
 313                    yield k, vs
 314
 315    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
 316        """
 317        Returns the first node in this tree which matches at least one of
 318        the specified types.
 319
 320        Args:
 321            expression_types: the expression type(s) to match.
 322
 323        Returns:
 324            The node which matches the criteria or None if no such node was found.
 325        """
 326        return next(self.find_all(*expression_types, bfs=bfs), None)
 327
 328    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
 329        """
 330        Returns a generator object which visits all nodes in this tree and only
 331        yields those that match at least one of the specified expression types.
 332
 333        Args:
 334            expression_types: the expression type(s) to match.
 335
 336        Returns:
 337            The generator object.
 338        """
 339        for expression, *_ in self.walk(bfs=bfs):
 340            if isinstance(expression, expression_types):
 341                yield expression
 342
 343    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
 344        """
 345        Returns a nearest parent matching expression_types.
 346
 347        Args:
 348            expression_types: the expression type(s) to match.
 349
 350        Returns:
 351            The parent node.
 352        """
 353        ancestor = self.parent
 354        while ancestor and not isinstance(ancestor, expression_types):
 355            ancestor = ancestor.parent
 356        return t.cast(E, ancestor)
 357
 358    @property
 359    def parent_select(self):
 360        """
 361        Returns the parent select statement.
 362        """
 363        return self.find_ancestor(Select)
 364
 365    @property
 366    def same_parent(self):
 367        """Returns if the parent is the same class as itself."""
 368        return type(self.parent) is self.__class__
 369
 370    def root(self) -> Expression:
 371        """
 372        Returns the root expression of this tree.
 373        """
 374        expression = self
 375        while expression.parent:
 376            expression = expression.parent
 377        return expression
 378
 379    def walk(self, bfs=True, prune=None):
 380        """
 381        Returns a generator object which visits all nodes in this tree.
 382
 383        Args:
 384            bfs (bool): if set to True the BFS traversal order will be applied,
 385                otherwise the DFS traversal will be used instead.
 386            prune ((node, parent, arg_key) -> bool): callable that returns True if
 387                the generator should stop traversing this branch of the tree.
 388
 389        Returns:
 390            the generator object.
 391        """
 392        if bfs:
 393            yield from self.bfs(prune=prune)
 394        else:
 395            yield from self.dfs(prune=prune)
 396
 397    def dfs(self, parent=None, key=None, prune=None):
 398        """
 399        Returns a generator object which visits all nodes in this tree in
 400        the DFS (Depth-first) order.
 401
 402        Returns:
 403            The generator object.
 404        """
 405        parent = parent or self.parent
 406        yield self, parent, key
 407        if prune and prune(self, parent, key):
 408            return
 409
 410        for k, v in self.iter_expressions():
 411            yield from v.dfs(self, k, prune)
 412
 413    def bfs(self, prune=None):
 414        """
 415        Returns a generator object which visits all nodes in this tree in
 416        the BFS (Breadth-first) order.
 417
 418        Returns:
 419            The generator object.
 420        """
 421        queue = deque([(self, self.parent, None)])
 422
 423        while queue:
 424            item, parent, key = queue.popleft()
 425
 426            yield item, parent, key
 427            if prune and prune(item, parent, key):
 428                continue
 429
 430            for k, v in item.iter_expressions():
 431                queue.append((v, item, k))
 432
 433    def unnest(self):
 434        """
 435        Returns the first non parenthesis child or self.
 436        """
 437        expression = self
 438        while type(expression) is Paren:
 439            expression = expression.this
 440        return expression
 441
 442    def unalias(self):
 443        """
 444        Returns the inner expression if this is an Alias.
 445        """
 446        if isinstance(self, Alias):
 447            return self.this
 448        return self
 449
 450    def unnest_operands(self):
 451        """
 452        Returns unnested operands as a tuple.
 453        """
 454        return tuple(arg.unnest() for _, arg in self.iter_expressions())
 455
 456    def flatten(self, unnest=True):
 457        """
 458        Returns a generator which yields child nodes who's parents are the same class.
 459
 460        A AND B AND C -> [A, B, C]
 461        """
 462        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
 463            if not type(node) is self.__class__:
 464                yield node.unnest() if unnest else node
 465
 466    def __str__(self):
 467        return self.sql()
 468
 469    def __repr__(self):
 470        return self._to_s()
 471
 472    def sql(self, dialect: DialectType = None, **opts) -> str:
 473        """
 474        Returns SQL string representation of this tree.
 475
 476        Args:
 477            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
 478            opts: other `sqlglot.generator.Generator` options.
 479
 480        Returns:
 481            The SQL string.
 482        """
 483        from sqlglot.dialects import Dialect
 484
 485        return Dialect.get_or_raise(dialect)().generate(self, **opts)
 486
 487    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
 488        indent = "" if not level else "\n"
 489        indent += "".join(["  "] * level)
 490        left = f"({self.key.upper()} "
 491
 492        args: t.Dict[str, t.Any] = {
 493            k: ", ".join(
 494                v._to_s(hide_missing=hide_missing, level=level + 1)
 495                if hasattr(v, "_to_s")
 496                else str(v)
 497                for v in ensure_list(vs)
 498                if v is not None
 499            )
 500            for k, vs in self.args.items()
 501        }
 502        args["comments"] = self.comments
 503        args["type"] = self.type
 504        args = {k: v for k, v in args.items() if v or not hide_missing}
 505
 506        right = ", ".join(f"{k}: {v}" for k, v in args.items())
 507        right += ")"
 508
 509        return indent + left + right
 510
 511    def transform(self, fun, *args, copy=True, **kwargs):
 512        """
 513        Recursively visits all tree nodes (excluding already transformed ones)
 514        and applies the given transformation function to each node.
 515
 516        Args:
 517            fun (function): a function which takes a node as an argument and returns a
 518                new transformed node or the same node without modifications. If the function
 519                returns None, then the corresponding node will be removed from the syntax tree.
 520            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
 521                modified in place.
 522
 523        Returns:
 524            The transformed tree.
 525        """
 526        node = self.copy() if copy else self
 527        new_node = fun(node, *args, **kwargs)
 528
 529        if new_node is None or not isinstance(new_node, Expression):
 530            return new_node
 531        if new_node is not node:
 532            new_node.parent = node.parent
 533            return new_node
 534
 535        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
 536        return new_node
 537
 538    def replace(self, expression):
 539        """
 540        Swap out this expression with a new expression.
 541
 542        For example::
 543
 544            >>> tree = Select().select("x").from_("tbl")
 545            >>> tree.find(Column).replace(Column(this="y"))
 546            (COLUMN this: y)
 547            >>> tree.sql()
 548            'SELECT y FROM tbl'
 549
 550        Args:
 551            expression (Expression|None): new node
 552
 553        Returns:
 554            The new expression or expressions.
 555        """
 556        if not self.parent:
 557            return expression
 558
 559        parent = self.parent
 560        self.parent = None
 561
 562        replace_children(parent, lambda child: expression if child is self else child)
 563        return expression
 564
 565    def pop(self):
 566        """
 567        Remove this expression from its AST.
 568
 569        Returns:
 570            The popped expression.
 571        """
 572        self.replace(None)
 573        return self
 574
 575    def assert_is(self, type_):
 576        """
 577        Assert that this `Expression` is an instance of `type_`.
 578
 579        If it is NOT an instance of `type_`, this raises an assertion error.
 580        Otherwise, this returns this expression.
 581
 582        Examples:
 583            This is useful for type security in chained expressions:
 584
 585            >>> import sqlglot
 586            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
 587            'SELECT x, z FROM y'
 588        """
 589        assert isinstance(self, type_)
 590        return self
 591
 592    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
 593        """
 594        Checks if this expression is valid (e.g. all mandatory args are set).
 595
 596        Args:
 597            args: a sequence of values that were used to instantiate a Func expression. This is used
 598                to check that the provided arguments don't exceed the function argument limit.
 599
 600        Returns:
 601            A list of error messages for all possible errors that were found.
 602        """
 603        errors: t.List[str] = []
 604
 605        for k in self.args:
 606            if k not in self.arg_types:
 607                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
 608        for k, mandatory in self.arg_types.items():
 609            v = self.args.get(k)
 610            if mandatory and (v is None or (isinstance(v, list) and not v)):
 611                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
 612
 613        if (
 614            args
 615            and isinstance(self, Func)
 616            and len(args) > len(self.arg_types)
 617            and not self.is_var_len_args
 618        ):
 619            errors.append(
 620                f"The number of provided arguments ({len(args)}) is greater than "
 621                f"the maximum number of supported arguments ({len(self.arg_types)})"
 622            )
 623
 624        return errors
 625
 626    def dump(self):
 627        """
 628        Dump this Expression to a JSON-serializable dict.
 629        """
 630        from sqlglot.serde import dump
 631
 632        return dump(self)
 633
 634    @classmethod
 635    def load(cls, obj):
 636        """
 637        Load a dict (as returned by `Expression.dump`) into an Expression instance.
 638        """
 639        from sqlglot.serde import load
 640
 641        return load(obj)
 642
 643
 644IntoType = t.Union[
 645    str,
 646    t.Type[Expression],
 647    t.Collection[t.Union[str, t.Type[Expression]]],
 648]
 649ExpOrStr = t.Union[str, Expression]
 650
 651
 652class Condition(Expression):
 653    def and_(self, *expressions, dialect=None, **opts):
 654        """
 655        AND this condition with one or multiple expressions.
 656
 657        Example:
 658            >>> condition("x=1").and_("y=1").sql()
 659            'x = 1 AND y = 1'
 660
 661        Args:
 662            *expressions (str | Expression): the SQL code strings to parse.
 663                If an `Expression` instance is passed, it will be used as-is.
 664            dialect (str): the dialect used to parse the input expression.
 665            opts (kwargs): other options to use to parse the input expressions.
 666
 667        Returns:
 668            And: the new condition.
 669        """
 670        return and_(self, *expressions, dialect=dialect, **opts)
 671
 672    def or_(self, *expressions, dialect=None, **opts):
 673        """
 674        OR this condition with one or multiple expressions.
 675
 676        Example:
 677            >>> condition("x=1").or_("y=1").sql()
 678            'x = 1 OR y = 1'
 679
 680        Args:
 681            *expressions (str | Expression): the SQL code strings to parse.
 682                If an `Expression` instance is passed, it will be used as-is.
 683            dialect (str): the dialect used to parse the input expression.
 684            opts (kwargs): other options to use to parse the input expressions.
 685
 686        Returns:
 687            Or: the new condition.
 688        """
 689        return or_(self, *expressions, dialect=dialect, **opts)
 690
 691    def not_(self):
 692        """
 693        Wrap this condition with NOT.
 694
 695        Example:
 696            >>> condition("x=1").not_().sql()
 697            'NOT x = 1'
 698
 699        Returns:
 700            Not: the new condition.
 701        """
 702        return not_(self)
 703
 704
 705class Predicate(Condition):
 706    """Relationships like x = y, x > 1, x >= y."""
 707
 708
 709class DerivedTable(Expression):
 710    @property
 711    def alias_column_names(self):
 712        table_alias = self.args.get("alias")
 713        if not table_alias:
 714            return []
 715        column_list = table_alias.assert_is(TableAlias).args.get("columns") or []
 716        return [c.name for c in column_list]
 717
 718    @property
 719    def selects(self):
 720        alias = self.args.get("alias")
 721
 722        if alias:
 723            return alias.columns
 724        return []
 725
 726    @property
 727    def named_selects(self):
 728        return [select.output_name for select in self.selects]
 729
 730
 731class Unionable(Expression):
 732    def union(self, expression, distinct=True, dialect=None, **opts):
 733        """
 734        Builds a UNION expression.
 735
 736        Example:
 737            >>> import sqlglot
 738            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
 739            'SELECT * FROM foo UNION SELECT * FROM bla'
 740
 741        Args:
 742            expression (str | Expression): the SQL code string.
 743                If an `Expression` instance is passed, it will be used as-is.
 744            distinct (bool): set the DISTINCT flag if and only if this is true.
 745            dialect (str): the dialect used to parse the input expression.
 746            opts (kwargs): other options to use to parse the input expressions.
 747        Returns:
 748            Union: the Union expression.
 749        """
 750        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 751
 752    def intersect(self, expression, distinct=True, dialect=None, **opts):
 753        """
 754        Builds an INTERSECT expression.
 755
 756        Example:
 757            >>> import sqlglot
 758            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
 759            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
 760
 761        Args:
 762            expression (str | Expression): the SQL code string.
 763                If an `Expression` instance is passed, it will be used as-is.
 764            distinct (bool): set the DISTINCT flag if and only if this is true.
 765            dialect (str): the dialect used to parse the input expression.
 766            opts (kwargs): other options to use to parse the input expressions.
 767        Returns:
 768            Intersect: the Intersect expression
 769        """
 770        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 771
 772    def except_(self, expression, distinct=True, dialect=None, **opts):
 773        """
 774        Builds an EXCEPT expression.
 775
 776        Example:
 777            >>> import sqlglot
 778            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
 779            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
 780
 781        Args:
 782            expression (str | Expression): the SQL code string.
 783                If an `Expression` instance is passed, it will be used as-is.
 784            distinct (bool): set the DISTINCT flag if and only if this is true.
 785            dialect (str): the dialect used to parse the input expression.
 786            opts (kwargs): other options to use to parse the input expressions.
 787        Returns:
 788            Except: the Except expression
 789        """
 790        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 791
 792
 793class UDTF(DerivedTable, Unionable):
 794    pass
 795
 796
 797class Cache(Expression):
 798    arg_types = {
 799        "with": False,
 800        "this": True,
 801        "lazy": False,
 802        "options": False,
 803        "expression": False,
 804    }
 805
 806
 807class Uncache(Expression):
 808    arg_types = {"this": True, "exists": False}
 809
 810
 811class Create(Expression):
 812    arg_types = {
 813        "with": False,
 814        "this": True,
 815        "kind": True,
 816        "expression": False,
 817        "exists": False,
 818        "properties": False,
 819        "replace": False,
 820        "unique": False,
 821        "indexes": False,
 822        "no_schema_binding": False,
 823        "begin": False,
 824    }
 825
 826
 827class Describe(Expression):
 828    arg_types = {"this": True, "kind": False}
 829
 830
 831class Pragma(Expression):
 832    pass
 833
 834
 835class Set(Expression):
 836    arg_types = {"expressions": False}
 837
 838
 839class SetItem(Expression):
 840    arg_types = {
 841        "this": False,
 842        "expressions": False,
 843        "kind": False,
 844        "collate": False,  # MySQL SET NAMES statement
 845        "global": False,
 846    }
 847
 848
 849class Show(Expression):
 850    arg_types = {
 851        "this": True,
 852        "target": False,
 853        "offset": False,
 854        "limit": False,
 855        "like": False,
 856        "where": False,
 857        "db": False,
 858        "full": False,
 859        "mutex": False,
 860        "query": False,
 861        "channel": False,
 862        "global": False,
 863        "log": False,
 864        "position": False,
 865        "types": False,
 866    }
 867
 868
 869class UserDefinedFunction(Expression):
 870    arg_types = {"this": True, "expressions": False, "wrapped": False}
 871
 872
 873class CharacterSet(Expression):
 874    arg_types = {"this": True, "default": False}
 875
 876
 877class With(Expression):
 878    arg_types = {"expressions": True, "recursive": False}
 879
 880    @property
 881    def recursive(self) -> bool:
 882        return bool(self.args.get("recursive"))
 883
 884
 885class WithinGroup(Expression):
 886    arg_types = {"this": True, "expression": False}
 887
 888
 889class CTE(DerivedTable):
 890    arg_types = {"this": True, "alias": True}
 891
 892
 893class TableAlias(Expression):
 894    arg_types = {"this": False, "columns": False}
 895
 896    @property
 897    def columns(self):
 898        return self.args.get("columns") or []
 899
 900
 901class BitString(Condition):
 902    pass
 903
 904
 905class HexString(Condition):
 906    pass
 907
 908
 909class ByteString(Condition):
 910    pass
 911
 912
 913class Column(Condition):
 914    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
 915
 916    @property
 917    def table(self) -> str:
 918        return self.text("table")
 919
 920    @property
 921    def db(self) -> str:
 922        return self.text("db")
 923
 924    @property
 925    def catalog(self) -> str:
 926        return self.text("catalog")
 927
 928    @property
 929    def output_name(self) -> str:
 930        return self.name
 931
 932    @property
 933    def parts(self) -> t.List[Identifier]:
 934        """Return the parts of a column in order catalog, db, table, name."""
 935        return [part for part in reversed(list(self.args.values())) if part]
 936
 937    def to_dot(self) -> Dot:
 938        """Converts the column into a dot expression."""
 939        parts = self.parts
 940        parent = self.parent
 941
 942        while parent:
 943            if isinstance(parent, Dot):
 944                parts.append(parent.expression)
 945            parent = parent.parent
 946
 947        return Dot.build(parts)
 948
 949
 950class ColumnPosition(Expression):
 951    arg_types = {"this": False, "position": True}
 952
 953
 954class ColumnDef(Expression):
 955    arg_types = {
 956        "this": True,
 957        "kind": False,
 958        "constraints": False,
 959        "exists": False,
 960        "position": False,
 961    }
 962
 963
 964class AlterColumn(Expression):
 965    arg_types = {
 966        "this": True,
 967        "dtype": False,
 968        "collate": False,
 969        "using": False,
 970        "default": False,
 971        "drop": False,
 972    }
 973
 974
 975class RenameTable(Expression):
 976    pass
 977
 978
 979class SetTag(Expression):
 980    arg_types = {"expressions": True, "unset": False}
 981
 982
 983class Comment(Expression):
 984    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
 985
 986
 987class ColumnConstraint(Expression):
 988    arg_types = {"this": False, "kind": True}
 989
 990
 991class ColumnConstraintKind(Expression):
 992    pass
 993
 994
 995class AutoIncrementColumnConstraint(ColumnConstraintKind):
 996    pass
 997
 998
 999class CaseSpecificColumnConstraint(ColumnConstraintKind):
1000    arg_types = {"not_": True}
1001
1002
1003class CharacterSetColumnConstraint(ColumnConstraintKind):
1004    arg_types = {"this": True}
1005
1006
1007class CheckColumnConstraint(ColumnConstraintKind):
1008    pass
1009
1010
1011class CollateColumnConstraint(ColumnConstraintKind):
1012    pass
1013
1014
1015class CommentColumnConstraint(ColumnConstraintKind):
1016    pass
1017
1018
1019class CompressColumnConstraint(ColumnConstraintKind):
1020    pass
1021
1022
1023class DateFormatColumnConstraint(ColumnConstraintKind):
1024    arg_types = {"this": True}
1025
1026
1027class DefaultColumnConstraint(ColumnConstraintKind):
1028    pass
1029
1030
1031class EncodeColumnConstraint(ColumnConstraintKind):
1032    pass
1033
1034
1035class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1036    # this: True -> ALWAYS, this: False -> BY DEFAULT
1037    arg_types = {
1038        "this": False,
1039        "start": False,
1040        "increment": False,
1041        "minvalue": False,
1042        "maxvalue": False,
1043        "cycle": False,
1044    }
1045
1046
1047class InlineLengthColumnConstraint(ColumnConstraintKind):
1048    pass
1049
1050
1051class NotNullColumnConstraint(ColumnConstraintKind):
1052    arg_types = {"allow_null": False}
1053
1054
1055# https://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html
1056class OnUpdateColumnConstraint(ColumnConstraintKind):
1057    pass
1058
1059
1060class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1061    arg_types = {"desc": False}
1062
1063
1064class TitleColumnConstraint(ColumnConstraintKind):
1065    pass
1066
1067
1068class UniqueColumnConstraint(ColumnConstraintKind):
1069    arg_types: t.Dict[str, t.Any] = {}
1070
1071
1072class UppercaseColumnConstraint(ColumnConstraintKind):
1073    arg_types: t.Dict[str, t.Any] = {}
1074
1075
1076class PathColumnConstraint(ColumnConstraintKind):
1077    pass
1078
1079
1080class Constraint(Expression):
1081    arg_types = {"this": True, "expressions": True}
1082
1083
1084class Delete(Expression):
1085    arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False}
1086
1087    def delete(
1088        self,
1089        table: ExpOrStr,
1090        dialect: DialectType = None,
1091        copy: bool = True,
1092        **opts,
1093    ) -> Delete:
1094        """
1095        Create a DELETE expression or replace the table on an existing DELETE expression.
1096
1097        Example:
1098            >>> delete("tbl").sql()
1099            'DELETE FROM tbl'
1100
1101        Args:
1102            table: the table from which to delete.
1103            dialect: the dialect used to parse the input expression.
1104            copy: if `False`, modify this expression instance in-place.
1105            opts: other options to use to parse the input expressions.
1106
1107        Returns:
1108            Delete: the modified expression.
1109        """
1110        return _apply_builder(
1111            expression=table,
1112            instance=self,
1113            arg="this",
1114            dialect=dialect,
1115            into=Table,
1116            copy=copy,
1117            **opts,
1118        )
1119
1120    def where(
1121        self,
1122        *expressions: ExpOrStr,
1123        append: bool = True,
1124        dialect: DialectType = None,
1125        copy: bool = True,
1126        **opts,
1127    ) -> Delete:
1128        """
1129        Append to or set the WHERE expressions.
1130
1131        Example:
1132            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1133            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1134
1135        Args:
1136            *expressions: the SQL code strings to parse.
1137                If an `Expression` instance is passed, it will be used as-is.
1138                Multiple expressions are combined with an AND operator.
1139            append: if `True`, AND the new expressions to any existing expression.
1140                Otherwise, this resets the expression.
1141            dialect: the dialect used to parse the input expressions.
1142            copy: if `False`, modify this expression instance in-place.
1143            opts: other options to use to parse the input expressions.
1144
1145        Returns:
1146            Delete: the modified expression.
1147        """
1148        return _apply_conjunction_builder(
1149            *expressions,
1150            instance=self,
1151            arg="where",
1152            append=append,
1153            into=Where,
1154            dialect=dialect,
1155            copy=copy,
1156            **opts,
1157        )
1158
1159    def returning(
1160        self,
1161        expression: ExpOrStr,
1162        dialect: DialectType = None,
1163        copy: bool = True,
1164        **opts,
1165    ) -> Delete:
1166        """
1167        Set the RETURNING expression. Not supported by all dialects.
1168
1169        Example:
1170            >>> delete("tbl").returning("*", dialect="postgres").sql()
1171            'DELETE FROM tbl RETURNING *'
1172
1173        Args:
1174            expression: the SQL code strings to parse.
1175                If an `Expression` instance is passed, it will be used as-is.
1176            dialect: the dialect used to parse the input expressions.
1177            copy: if `False`, modify this expression instance in-place.
1178            opts: other options to use to parse the input expressions.
1179
1180        Returns:
1181            Delete: the modified expression.
1182        """
1183        return _apply_builder(
1184            expression=expression,
1185            instance=self,
1186            arg="returning",
1187            prefix="RETURNING",
1188            dialect=dialect,
1189            copy=copy,
1190            into=Returning,
1191            **opts,
1192        )
1193
1194
1195class Drop(Expression):
1196    arg_types = {
1197        "this": False,
1198        "kind": False,
1199        "exists": False,
1200        "temporary": False,
1201        "materialized": False,
1202        "cascade": False,
1203        "constraints": False,
1204        "purge": False,
1205    }
1206
1207
1208class Filter(Expression):
1209    arg_types = {"this": True, "expression": True}
1210
1211
1212class Check(Expression):
1213    pass
1214
1215
1216class Directory(Expression):
1217    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1218    arg_types = {"this": True, "local": False, "row_format": False}
1219
1220
1221class ForeignKey(Expression):
1222    arg_types = {
1223        "expressions": True,
1224        "reference": False,
1225        "delete": False,
1226        "update": False,
1227    }
1228
1229
1230class PrimaryKey(Expression):
1231    arg_types = {"expressions": True, "options": False}
1232
1233
1234class Unique(Expression):
1235    arg_types = {"expressions": True}
1236
1237
1238# https://www.postgresql.org/docs/9.1/sql-selectinto.html
1239# https://docs.aws.amazon.com/redshift/latest/dg/r_SELECT_INTO.html#r_SELECT_INTO-examples
1240class Into(Expression):
1241    arg_types = {"this": True, "temporary": False, "unlogged": False}
1242
1243
1244class From(Expression):
1245    arg_types = {"expressions": True}
1246
1247
1248class Having(Expression):
1249    pass
1250
1251
1252class Hint(Expression):
1253    arg_types = {"expressions": True}
1254
1255
1256class JoinHint(Expression):
1257    arg_types = {"this": True, "expressions": True}
1258
1259
1260class Identifier(Expression):
1261    arg_types = {"this": True, "quoted": False}
1262
1263    @property
1264    def quoted(self):
1265        return bool(self.args.get("quoted"))
1266
1267    @property
1268    def hashable_args(self) -> t.Any:
1269        if self.quoted and any(char.isupper() for char in self.this):
1270            return (self.this, self.quoted)
1271        return self.this.lower()
1272
1273    @property
1274    def output_name(self):
1275        return self.name
1276
1277
1278class Index(Expression):
1279    arg_types = {
1280        "this": False,
1281        "table": False,
1282        "where": False,
1283        "columns": False,
1284        "unique": False,
1285        "primary": False,
1286        "amp": False,  # teradata
1287    }
1288
1289
1290class Insert(Expression):
1291    arg_types = {
1292        "with": False,
1293        "this": True,
1294        "expression": False,
1295        "returning": False,
1296        "overwrite": False,
1297        "exists": False,
1298        "partition": False,
1299        "alternative": False,
1300    }
1301
1302
1303class Returning(Expression):
1304    arg_types = {"expressions": True}
1305
1306
1307# https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html
1308class Introducer(Expression):
1309    arg_types = {"this": True, "expression": True}
1310
1311
1312# national char, like n'utf8'
1313class National(Expression):
1314    pass
1315
1316
1317class LoadData(Expression):
1318    arg_types = {
1319        "this": True,
1320        "local": False,
1321        "overwrite": False,
1322        "inpath": True,
1323        "partition": False,
1324        "input_format": False,
1325        "serde": False,
1326    }
1327
1328
1329class Partition(Expression):
1330    arg_types = {"expressions": True}
1331
1332
1333class Fetch(Expression):
1334    arg_types = {
1335        "direction": False,
1336        "count": False,
1337        "percent": False,
1338        "with_ties": False,
1339    }
1340
1341
1342class Group(Expression):
1343    arg_types = {
1344        "expressions": False,
1345        "grouping_sets": False,
1346        "cube": False,
1347        "rollup": False,
1348    }
1349
1350
1351class Lambda(Expression):
1352    arg_types = {"this": True, "expressions": True}
1353
1354
1355class Limit(Expression):
1356    arg_types = {"this": False, "expression": True}
1357
1358
1359class Literal(Condition):
1360    arg_types = {"this": True, "is_string": True}
1361
1362    @property
1363    def hashable_args(self) -> t.Any:
1364        return (self.this, self.args.get("is_string"))
1365
1366    @classmethod
1367    def number(cls, number) -> Literal:
1368        return cls(this=str(number), is_string=False)
1369
1370    @classmethod
1371    def string(cls, string) -> Literal:
1372        return cls(this=str(string), is_string=True)
1373
1374    @property
1375    def output_name(self):
1376        return self.name
1377
1378
1379class Join(Expression):
1380    arg_types = {
1381        "this": True,
1382        "on": False,
1383        "side": False,
1384        "kind": False,
1385        "using": False,
1386        "natural": False,
1387        "hint": False,
1388    }
1389
1390    @property
1391    def kind(self):
1392        return self.text("kind").upper()
1393
1394    @property
1395    def side(self):
1396        return self.text("side").upper()
1397
1398    @property
1399    def hint(self):
1400        return self.text("hint").upper()
1401
1402    @property
1403    def alias_or_name(self):
1404        return self.this.alias_or_name
1405
1406    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1407        """
1408        Append to or set the ON expressions.
1409
1410        Example:
1411            >>> import sqlglot
1412            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1413            'JOIN x ON y = 1'
1414
1415        Args:
1416            *expressions (str | Expression): the SQL code strings to parse.
1417                If an `Expression` instance is passed, it will be used as-is.
1418                Multiple expressions are combined with an AND operator.
1419            append (bool): if `True`, AND the new expressions to any existing expression.
1420                Otherwise, this resets the expression.
1421            dialect (str): the dialect used to parse the input expressions.
1422            copy (bool): if `False`, modify this expression instance in-place.
1423            opts (kwargs): other options to use to parse the input expressions.
1424
1425        Returns:
1426            Join: the modified join expression.
1427        """
1428        join = _apply_conjunction_builder(
1429            *expressions,
1430            instance=self,
1431            arg="on",
1432            append=append,
1433            dialect=dialect,
1434            copy=copy,
1435            **opts,
1436        )
1437
1438        if join.kind == "CROSS":
1439            join.set("kind", None)
1440
1441        return join
1442
1443    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1444        """
1445        Append to or set the USING expressions.
1446
1447        Example:
1448            >>> import sqlglot
1449            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1450            'JOIN x USING (foo, bla)'
1451
1452        Args:
1453            *expressions (str | Expression): the SQL code strings to parse.
1454                If an `Expression` instance is passed, it will be used as-is.
1455            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1456                Otherwise, this resets the expression.
1457            dialect (str): the dialect used to parse the input expressions.
1458            copy (bool): if `False`, modify this expression instance in-place.
1459            opts (kwargs): other options to use to parse the input expressions.
1460
1461        Returns:
1462            Join: the modified join expression.
1463        """
1464        join = _apply_list_builder(
1465            *expressions,
1466            instance=self,
1467            arg="using",
1468            append=append,
1469            dialect=dialect,
1470            copy=copy,
1471            **opts,
1472        )
1473
1474        if join.kind == "CROSS":
1475            join.set("kind", None)
1476
1477        return join
1478
1479
1480class Lateral(UDTF):
1481    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
1482
1483
1484class MatchRecognize(Expression):
1485    arg_types = {
1486        "partition_by": False,
1487        "order": False,
1488        "measures": False,
1489        "rows": False,
1490        "after": False,
1491        "pattern": False,
1492        "define": False,
1493        "alias": False,
1494    }
1495
1496
1497# Clickhouse FROM FINAL modifier
1498# https://clickhouse.com/docs/en/sql-reference/statements/select/from/#final-modifier
1499class Final(Expression):
1500    pass
1501
1502
1503class Offset(Expression):
1504    arg_types = {"this": False, "expression": True}
1505
1506
1507class Order(Expression):
1508    arg_types = {"this": False, "expressions": True}
1509
1510
1511# hive specific sorts
1512# https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SortBy
1513class Cluster(Order):
1514    pass
1515
1516
1517class Distribute(Order):
1518    pass
1519
1520
1521class Sort(Order):
1522    pass
1523
1524
1525class Ordered(Expression):
1526    arg_types = {"this": True, "desc": True, "nulls_first": True}
1527
1528
1529class Property(Expression):
1530    arg_types = {"this": True, "value": True}
1531
1532
1533class AfterJournalProperty(Property):
1534    arg_types = {"no": True, "dual": False, "local": False}
1535
1536
1537class AlgorithmProperty(Property):
1538    arg_types = {"this": True}
1539
1540
1541class AutoIncrementProperty(Property):
1542    arg_types = {"this": True}
1543
1544
1545class BlockCompressionProperty(Property):
1546    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
1547
1548
1549class CharacterSetProperty(Property):
1550    arg_types = {"this": True, "default": True}
1551
1552
1553class ChecksumProperty(Property):
1554    arg_types = {"on": False, "default": False}
1555
1556
1557class CollateProperty(Property):
1558    arg_types = {"this": True}
1559
1560
1561class DataBlocksizeProperty(Property):
1562    arg_types = {"size": False, "units": False, "min": False, "default": False}
1563
1564
1565class DefinerProperty(Property):
1566    arg_types = {"this": True}
1567
1568
1569class DistKeyProperty(Property):
1570    arg_types = {"this": True}
1571
1572
1573class DistStyleProperty(Property):
1574    arg_types = {"this": True}
1575
1576
1577class EngineProperty(Property):
1578    arg_types = {"this": True}
1579
1580
1581class ExecuteAsProperty(Property):
1582    arg_types = {"this": True}
1583
1584
1585class ExternalProperty(Property):
1586    arg_types = {"this": False}
1587
1588
1589class FallbackProperty(Property):
1590    arg_types = {"no": True, "protection": False}
1591
1592
1593class FileFormatProperty(Property):
1594    arg_types = {"this": True}
1595
1596
1597class FreespaceProperty(Property):
1598    arg_types = {"this": True, "percent": False}
1599
1600
1601class InputOutputFormat(Expression):
1602    arg_types = {"input_format": False, "output_format": False}
1603
1604
1605class IsolatedLoadingProperty(Property):
1606    arg_types = {
1607        "no": True,
1608        "concurrent": True,
1609        "for_all": True,
1610        "for_insert": True,
1611        "for_none": True,
1612    }
1613
1614
1615class JournalProperty(Property):
1616    arg_types = {"no": True, "dual": False, "before": False}
1617
1618
1619class LanguageProperty(Property):
1620    arg_types = {"this": True}
1621
1622
1623class LikeProperty(Property):
1624    arg_types = {"this": True, "expressions": False}
1625
1626
1627class LocationProperty(Property):
1628    arg_types = {"this": True}
1629
1630
1631class LockingProperty(Property):
1632    arg_types = {
1633        "this": False,
1634        "kind": True,
1635        "for_or_in": True,
1636        "lock_type": True,
1637        "override": False,
1638    }
1639
1640
1641class LogProperty(Property):
1642    arg_types = {"no": True}
1643
1644
1645class MaterializedProperty(Property):
1646    arg_types = {"this": False}
1647
1648
1649class MergeBlockRatioProperty(Property):
1650    arg_types = {"this": False, "no": False, "default": False, "percent": False}
1651
1652
1653class NoPrimaryIndexProperty(Property):
1654    arg_types = {"this": False}
1655
1656
1657class OnCommitProperty(Property):
1658    arg_type = {"this": False}
1659
1660
1661class PartitionedByProperty(Property):
1662    arg_types = {"this": True}
1663
1664
1665class ReturnsProperty(Property):
1666    arg_types = {"this": True, "is_table": False, "table": False}
1667
1668
1669class RowFormatProperty(Property):
1670    arg_types = {"this": True}
1671
1672
1673class RowFormatDelimitedProperty(Property):
1674    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
1675    arg_types = {
1676        "fields": False,
1677        "escaped": False,
1678        "collection_items": False,
1679        "map_keys": False,
1680        "lines": False,
1681        "null": False,
1682        "serde": False,
1683    }
1684
1685
1686class RowFormatSerdeProperty(Property):
1687    arg_types = {"this": True}
1688
1689
1690class SchemaCommentProperty(Property):
1691    arg_types = {"this": True}
1692
1693
1694class SerdeProperties(Property):
1695    arg_types = {"expressions": True}
1696
1697
1698class SetProperty(Property):
1699    arg_types = {"multi": True}
1700
1701
1702class SortKeyProperty(Property):
1703    arg_types = {"this": True, "compound": False}
1704
1705
1706class SqlSecurityProperty(Property):
1707    arg_types = {"definer": True}
1708
1709
1710class StabilityProperty(Property):
1711    arg_types = {"this": True}
1712
1713
1714class TableFormatProperty(Property):
1715    arg_types = {"this": True}
1716
1717
1718class TemporaryProperty(Property):
1719    arg_types = {"global_": True}
1720
1721
1722class TransientProperty(Property):
1723    arg_types = {"this": False}
1724
1725
1726class VolatileProperty(Property):
1727    arg_types = {"this": False}
1728
1729
1730class WithDataProperty(Property):
1731    arg_types = {"no": True, "statistics": False}
1732
1733
1734class WithJournalTableProperty(Property):
1735    arg_types = {"this": True}
1736
1737
1738class Properties(Expression):
1739    arg_types = {"expressions": True}
1740
1741    NAME_TO_PROPERTY = {
1742        "ALGORITHM": AlgorithmProperty,
1743        "AUTO_INCREMENT": AutoIncrementProperty,
1744        "CHARACTER SET": CharacterSetProperty,
1745        "COLLATE": CollateProperty,
1746        "COMMENT": SchemaCommentProperty,
1747        "DEFINER": DefinerProperty,
1748        "DISTKEY": DistKeyProperty,
1749        "DISTSTYLE": DistStyleProperty,
1750        "ENGINE": EngineProperty,
1751        "EXECUTE AS": ExecuteAsProperty,
1752        "FORMAT": FileFormatProperty,
1753        "LANGUAGE": LanguageProperty,
1754        "LOCATION": LocationProperty,
1755        "PARTITIONED_BY": PartitionedByProperty,
1756        "RETURNS": ReturnsProperty,
1757        "ROW_FORMAT": RowFormatProperty,
1758        "SORTKEY": SortKeyProperty,
1759        "TABLE_FORMAT": TableFormatProperty,
1760    }
1761
1762    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
1763
1764    # CREATE property locations
1765    # Form: schema specified
1766    #   create [POST_CREATE]
1767    #     table a [POST_NAME]
1768    #     (b int) [POST_SCHEMA]
1769    #     with ([POST_WITH])
1770    #     index (b) [POST_INDEX]
1771    #
1772    # Form: alias selection
1773    #   create [POST_CREATE]
1774    #     table a [POST_NAME]
1775    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
1776    #     index (c) [POST_INDEX]
1777    class Location(AutoName):
1778        POST_CREATE = auto()
1779        POST_NAME = auto()
1780        POST_SCHEMA = auto()
1781        POST_WITH = auto()
1782        POST_ALIAS = auto()
1783        POST_EXPRESSION = auto()
1784        POST_INDEX = auto()
1785        UNSUPPORTED = auto()
1786
1787    @classmethod
1788    def from_dict(cls, properties_dict) -> Properties:
1789        expressions = []
1790        for key, value in properties_dict.items():
1791            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1792            if property_cls:
1793                expressions.append(property_cls(this=convert(value)))
1794            else:
1795                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1796
1797        return cls(expressions=expressions)
1798
1799
1800class Qualify(Expression):
1801    pass
1802
1803
1804# https://www.ibm.com/docs/en/ias?topic=procedures-return-statement-in-sql
1805class Return(Expression):
1806    pass
1807
1808
1809class Reference(Expression):
1810    arg_types = {"this": True, "expressions": False, "options": False}
1811
1812
1813class Tuple(Expression):
1814    arg_types = {"expressions": False}
1815
1816
1817class Subqueryable(Unionable):
1818    def subquery(self, alias=None, copy=True) -> Subquery:
1819        """
1820        Convert this expression to an aliased expression that can be used as a Subquery.
1821
1822        Example:
1823            >>> subquery = Select().select("x").from_("tbl").subquery()
1824            >>> Select().select("x").from_(subquery).sql()
1825            'SELECT x FROM (SELECT x FROM tbl)'
1826
1827        Args:
1828            alias (str | Identifier): an optional alias for the subquery
1829            copy (bool): if `False`, modify this expression instance in-place.
1830
1831        Returns:
1832            Alias: the subquery
1833        """
1834        instance = _maybe_copy(self, copy)
1835        return Subquery(
1836            this=instance,
1837            alias=TableAlias(this=to_identifier(alias)) if alias else None,
1838        )
1839
1840    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1841        raise NotImplementedError
1842
1843    @property
1844    def ctes(self):
1845        with_ = self.args.get("with")
1846        if not with_:
1847            return []
1848        return with_.expressions
1849
1850    @property
1851    def selects(self):
1852        raise NotImplementedError("Subqueryable objects must implement `selects`")
1853
1854    @property
1855    def named_selects(self):
1856        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
1857
1858    def with_(
1859        self,
1860        alias,
1861        as_,
1862        recursive=None,
1863        append=True,
1864        dialect=None,
1865        copy=True,
1866        **opts,
1867    ):
1868        """
1869        Append to or set the common table expressions.
1870
1871        Example:
1872            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
1873            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
1874
1875        Args:
1876            alias (str | Expression): the SQL code string to parse as the table name.
1877                If an `Expression` instance is passed, this is used as-is.
1878            as_ (str | Expression): the SQL code string to parse as the table expression.
1879                If an `Expression` instance is passed, it will be used as-is.
1880            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
1881            append (bool): if `True`, add to any existing expressions.
1882                Otherwise, this resets the expressions.
1883            dialect (str): the dialect used to parse the input expression.
1884            copy (bool): if `False`, modify this expression instance in-place.
1885            opts (kwargs): other options to use to parse the input expressions.
1886
1887        Returns:
1888            Select: the modified expression.
1889        """
1890        alias_expression = maybe_parse(
1891            alias,
1892            dialect=dialect,
1893            into=TableAlias,
1894            **opts,
1895        )
1896        as_expression = maybe_parse(
1897            as_,
1898            dialect=dialect,
1899            **opts,
1900        )
1901        cte = CTE(
1902            this=as_expression,
1903            alias=alias_expression,
1904        )
1905        return _apply_child_list_builder(
1906            cte,
1907            instance=self,
1908            arg="with",
1909            append=append,
1910            copy=copy,
1911            into=With,
1912            properties={"recursive": recursive or False},
1913        )
1914
1915
1916QUERY_MODIFIERS = {
1917    "match": False,
1918    "laterals": False,
1919    "joins": False,
1920    "pivots": False,
1921    "where": False,
1922    "group": False,
1923    "having": False,
1924    "qualify": False,
1925    "windows": False,
1926    "distribute": False,
1927    "sort": False,
1928    "cluster": False,
1929    "order": False,
1930    "limit": False,
1931    "offset": False,
1932    "lock": False,
1933    "sample": False,
1934}
1935
1936
1937class Table(Expression):
1938    arg_types = {
1939        "this": True,
1940        "alias": False,
1941        "db": False,
1942        "catalog": False,
1943        "laterals": False,
1944        "joins": False,
1945        "pivots": False,
1946        "hints": False,
1947        "system_time": False,
1948    }
1949
1950    @property
1951    def db(self) -> str:
1952        return self.text("db")
1953
1954    @property
1955    def catalog(self) -> str:
1956        return self.text("catalog")
1957
1958
1959# See the TSQL "Querying data in a system-versioned temporal table" page
1960class SystemTime(Expression):
1961    arg_types = {
1962        "this": False,
1963        "expression": False,
1964        "kind": True,
1965    }
1966
1967
1968class Union(Subqueryable):
1969    arg_types = {
1970        "with": False,
1971        "this": True,
1972        "expression": True,
1973        "distinct": False,
1974        **QUERY_MODIFIERS,
1975    }
1976
1977    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1978        """
1979        Set the LIMIT expression.
1980
1981        Example:
1982            >>> select("1").union(select("1")).limit(1).sql()
1983            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
1984
1985        Args:
1986            expression (str | int | Expression): the SQL code string to parse.
1987                This can also be an integer.
1988                If a `Limit` instance is passed, this is used as-is.
1989                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
1990            dialect (str): the dialect used to parse the input expression.
1991            copy (bool): if `False`, modify this expression instance in-place.
1992            opts (kwargs): other options to use to parse the input expressions.
1993
1994        Returns:
1995            Select: The limited subqueryable.
1996        """
1997        return (
1998            select("*")
1999            .from_(self.subquery(alias="_l_0", copy=copy))
2000            .limit(expression, dialect=dialect, copy=False, **opts)
2001        )
2002
2003    def select(
2004        self,
2005        *expressions: ExpOrStr,
2006        append: bool = True,
2007        dialect: DialectType = None,
2008        copy: bool = True,
2009        **opts,
2010    ) -> Union:
2011        """Append to or set the SELECT of the union recursively.
2012
2013        Example:
2014            >>> from sqlglot import parse_one
2015            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2016            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2017
2018        Args:
2019            *expressions: the SQL code strings to parse.
2020                If an `Expression` instance is passed, it will be used as-is.
2021            append: if `True`, add to any existing expressions.
2022                Otherwise, this resets the expressions.
2023            dialect: the dialect used to parse the input expressions.
2024            copy: if `False`, modify this expression instance in-place.
2025            opts: other options to use to parse the input expressions.
2026
2027        Returns:
2028            Union: the modified expression.
2029        """
2030        this = self.copy() if copy else self
2031        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2032        this.expression.unnest().select(
2033            *expressions, append=append, dialect=dialect, copy=False, **opts
2034        )
2035        return this
2036
2037    @property
2038    def named_selects(self):
2039        return self.this.unnest().named_selects
2040
2041    @property
2042    def is_star(self) -> bool:
2043        return self.this.is_star or self.expression.is_star
2044
2045    @property
2046    def selects(self):
2047        return self.this.unnest().selects
2048
2049    @property
2050    def left(self):
2051        return self.this
2052
2053    @property
2054    def right(self):
2055        return self.expression
2056
2057
2058class Except(Union):
2059    pass
2060
2061
2062class Intersect(Union):
2063    pass
2064
2065
2066class Unnest(UDTF):
2067    arg_types = {
2068        "expressions": True,
2069        "ordinality": False,
2070        "alias": False,
2071        "offset": False,
2072    }
2073
2074
2075class Update(Expression):
2076    arg_types = {
2077        "with": False,
2078        "this": False,
2079        "expressions": True,
2080        "from": False,
2081        "where": False,
2082        "returning": False,
2083    }
2084
2085
2086class Values(UDTF):
2087    arg_types = {
2088        "expressions": True,
2089        "ordinality": False,
2090        "alias": False,
2091    }
2092
2093
2094class Var(Expression):
2095    pass
2096
2097
2098class Schema(Expression):
2099    arg_types = {"this": False, "expressions": False}
2100
2101
2102# Used to represent the FOR UPDATE and FOR SHARE locking read types.
2103# https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html
2104class Lock(Expression):
2105    arg_types = {"update": True}
2106
2107
2108class Select(Subqueryable):
2109    arg_types = {
2110        "with": False,
2111        "kind": False,
2112        "expressions": False,
2113        "hint": False,
2114        "distinct": False,
2115        "into": False,
2116        "from": False,
2117        **QUERY_MODIFIERS,
2118    }
2119
2120    def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2121        """
2122        Set the FROM expression.
2123
2124        Example:
2125            >>> Select().from_("tbl").select("x").sql()
2126            'SELECT x FROM tbl'
2127
2128        Args:
2129            *expressions (str | Expression): the SQL code strings to parse.
2130                If a `From` instance is passed, this is used as-is.
2131                If another `Expression` instance is passed, it will be wrapped in a `From`.
2132            append (bool): if `True`, add to any existing expressions.
2133                Otherwise, this flattens all the `From` expression into a single expression.
2134            dialect (str): the dialect used to parse the input expression.
2135            copy (bool): if `False`, modify this expression instance in-place.
2136            opts (kwargs): other options to use to parse the input expressions.
2137
2138        Returns:
2139            Select: the modified expression.
2140        """
2141        return _apply_child_list_builder(
2142            *expressions,
2143            instance=self,
2144            arg="from",
2145            append=append,
2146            copy=copy,
2147            prefix="FROM",
2148            into=From,
2149            dialect=dialect,
2150            **opts,
2151        )
2152
2153    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2154        """
2155        Set the GROUP BY expression.
2156
2157        Example:
2158            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2159            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2160
2161        Args:
2162            *expressions (str | Expression): the SQL code strings to parse.
2163                If a `Group` instance is passed, this is used as-is.
2164                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2165                If nothing is passed in then a group by is not applied to the expression
2166            append (bool): if `True`, add to any existing expressions.
2167                Otherwise, this flattens all the `Group` expression into a single expression.
2168            dialect (str): the dialect used to parse the input expression.
2169            copy (bool): if `False`, modify this expression instance in-place.
2170            opts (kwargs): other options to use to parse the input expressions.
2171
2172        Returns:
2173            Select: the modified expression.
2174        """
2175        if not expressions:
2176            return self if not copy else self.copy()
2177        return _apply_child_list_builder(
2178            *expressions,
2179            instance=self,
2180            arg="group",
2181            append=append,
2182            copy=copy,
2183            prefix="GROUP BY",
2184            into=Group,
2185            dialect=dialect,
2186            **opts,
2187        )
2188
2189    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2190        """
2191        Set the ORDER BY expression.
2192
2193        Example:
2194            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2195            'SELECT x FROM tbl ORDER BY x DESC'
2196
2197        Args:
2198            *expressions (str | Expression): the SQL code strings to parse.
2199                If a `Group` instance is passed, this is used as-is.
2200                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2201            append (bool): if `True`, add to any existing expressions.
2202                Otherwise, this flattens all the `Order` expression into a single expression.
2203            dialect (str): the dialect used to parse the input expression.
2204            copy (bool): if `False`, modify this expression instance in-place.
2205            opts (kwargs): other options to use to parse the input expressions.
2206
2207        Returns:
2208            Select: the modified expression.
2209        """
2210        return _apply_child_list_builder(
2211            *expressions,
2212            instance=self,
2213            arg="order",
2214            append=append,
2215            copy=copy,
2216            prefix="ORDER BY",
2217            into=Order,
2218            dialect=dialect,
2219            **opts,
2220        )
2221
2222    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2223        """
2224        Set the SORT BY expression.
2225
2226        Example:
2227            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
2228            'SELECT x FROM tbl SORT BY x DESC'
2229
2230        Args:
2231            *expressions (str | Expression): the SQL code strings to parse.
2232                If a `Group` instance is passed, this is used as-is.
2233                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2234            append (bool): if `True`, add to any existing expressions.
2235                Otherwise, this flattens all the `Order` expression into a single expression.
2236            dialect (str): the dialect used to parse the input expression.
2237            copy (bool): if `False`, modify this expression instance in-place.
2238            opts (kwargs): other options to use to parse the input expressions.
2239
2240        Returns:
2241            Select: the modified expression.
2242        """
2243        return _apply_child_list_builder(
2244            *expressions,
2245            instance=self,
2246            arg="sort",
2247            append=append,
2248            copy=copy,
2249            prefix="SORT BY",
2250            into=Sort,
2251            dialect=dialect,
2252            **opts,
2253        )
2254
2255    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2256        """
2257        Set the CLUSTER BY expression.
2258
2259        Example:
2260            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
2261            'SELECT x FROM tbl CLUSTER BY x DESC'
2262
2263        Args:
2264            *expressions (str | Expression): the SQL code strings to parse.
2265                If a `Group` instance is passed, this is used as-is.
2266                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2267            append (bool): if `True`, add to any existing expressions.
2268                Otherwise, this flattens all the `Order` expression into a single expression.
2269            dialect (str): the dialect used to parse the input expression.
2270            copy (bool): if `False`, modify this expression instance in-place.
2271            opts (kwargs): other options to use to parse the input expressions.
2272
2273        Returns:
2274            Select: the modified expression.
2275        """
2276        return _apply_child_list_builder(
2277            *expressions,
2278            instance=self,
2279            arg="cluster",
2280            append=append,
2281            copy=copy,
2282            prefix="CLUSTER BY",
2283            into=Cluster,
2284            dialect=dialect,
2285            **opts,
2286        )
2287
2288    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2289        """
2290        Set the LIMIT expression.
2291
2292        Example:
2293            >>> Select().from_("tbl").select("x").limit(10).sql()
2294            'SELECT x FROM tbl LIMIT 10'
2295
2296        Args:
2297            expression (str | int | Expression): the SQL code string to parse.
2298                This can also be an integer.
2299                If a `Limit` instance is passed, this is used as-is.
2300                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2301            dialect (str): the dialect used to parse the input expression.
2302            copy (bool): if `False`, modify this expression instance in-place.
2303            opts (kwargs): other options to use to parse the input expressions.
2304
2305        Returns:
2306            Select: the modified expression.
2307        """
2308        return _apply_builder(
2309            expression=expression,
2310            instance=self,
2311            arg="limit",
2312            into=Limit,
2313            prefix="LIMIT",
2314            dialect=dialect,
2315            copy=copy,
2316            **opts,
2317        )
2318
2319    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2320        """
2321        Set the OFFSET expression.
2322
2323        Example:
2324            >>> Select().from_("tbl").select("x").offset(10).sql()
2325            'SELECT x FROM tbl OFFSET 10'
2326
2327        Args:
2328            expression (str | int | Expression): the SQL code string to parse.
2329                This can also be an integer.
2330                If a `Offset` instance is passed, this is used as-is.
2331                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2332            dialect (str): the dialect used to parse the input expression.
2333            copy (bool): if `False`, modify this expression instance in-place.
2334            opts (kwargs): other options to use to parse the input expressions.
2335
2336        Returns:
2337            Select: the modified expression.
2338        """
2339        return _apply_builder(
2340            expression=expression,
2341            instance=self,
2342            arg="offset",
2343            into=Offset,
2344            prefix="OFFSET",
2345            dialect=dialect,
2346            copy=copy,
2347            **opts,
2348        )
2349
2350    def select(
2351        self,
2352        *expressions: ExpOrStr,
2353        append: bool = True,
2354        dialect: DialectType = None,
2355        copy: bool = True,
2356        **opts,
2357    ) -> Select:
2358        """
2359        Append to or set the SELECT expressions.
2360
2361        Example:
2362            >>> Select().select("x", "y").sql()
2363            'SELECT x, y'
2364
2365        Args:
2366            *expressions: the SQL code strings to parse.
2367                If an `Expression` instance is passed, it will be used as-is.
2368            append: if `True`, add to any existing expressions.
2369                Otherwise, this resets the expressions.
2370            dialect: the dialect used to parse the input expressions.
2371            copy: if `False`, modify this expression instance in-place.
2372            opts: other options to use to parse the input expressions.
2373
2374        Returns:
2375            Select: the modified expression.
2376        """
2377        return _apply_list_builder(
2378            *expressions,
2379            instance=self,
2380            arg="expressions",
2381            append=append,
2382            dialect=dialect,
2383            copy=copy,
2384            **opts,
2385        )
2386
2387    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2388        """
2389        Append to or set the LATERAL expressions.
2390
2391        Example:
2392            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2393            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2394
2395        Args:
2396            *expressions (str | Expression): the SQL code strings to parse.
2397                If an `Expression` instance is passed, it will be used as-is.
2398            append (bool): if `True`, add to any existing expressions.
2399                Otherwise, this resets the expressions.
2400            dialect (str): the dialect used to parse the input expressions.
2401            copy (bool): if `False`, modify this expression instance in-place.
2402            opts (kwargs): other options to use to parse the input expressions.
2403
2404        Returns:
2405            Select: the modified expression.
2406        """
2407        return _apply_list_builder(
2408            *expressions,
2409            instance=self,
2410            arg="laterals",
2411            append=append,
2412            into=Lateral,
2413            prefix="LATERAL VIEW",
2414            dialect=dialect,
2415            copy=copy,
2416            **opts,
2417        )
2418
2419    def join(
2420        self,
2421        expression,
2422        on=None,
2423        using=None,
2424        append=True,
2425        join_type=None,
2426        join_alias=None,
2427        dialect=None,
2428        copy=True,
2429        **opts,
2430    ) -> Select:
2431        """
2432        Append to or set the JOIN expressions.
2433
2434        Example:
2435            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2436            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2437
2438            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2439            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2440
2441            Use `join_type` to change the type of join:
2442
2443            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2444            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2445
2446        Args:
2447            expression (str | Expression): the SQL code string to parse.
2448                If an `Expression` instance is passed, it will be used as-is.
2449            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2450                If an `Expression` instance is passed, it will be used as-is.
2451            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2452                If an `Expression` instance is passed, it will be used as-is.
2453            append (bool): if `True`, add to any existing expressions.
2454                Otherwise, this resets the expressions.
2455            join_type (str): If set, alter the parsed join type
2456            dialect (str): the dialect used to parse the input expressions.
2457            copy (bool): if `False`, modify this expression instance in-place.
2458            opts (kwargs): other options to use to parse the input expressions.
2459
2460        Returns:
2461            Select: the modified expression.
2462        """
2463        parse_args = {"dialect": dialect, **opts}
2464
2465        try:
2466            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2467        except ParseError:
2468            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2469
2470        join = expression if isinstance(expression, Join) else Join(this=expression)
2471
2472        if isinstance(join.this, Select):
2473            join.this.replace(join.this.subquery())
2474
2475        if join_type:
2476            natural: t.Optional[Token]
2477            side: t.Optional[Token]
2478            kind: t.Optional[Token]
2479
2480            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2481
2482            if natural:
2483                join.set("natural", True)
2484            if side:
2485                join.set("side", side.text)
2486            if kind:
2487                join.set("kind", kind.text)
2488
2489        if on:
2490            on = and_(*ensure_collection(on), dialect=dialect, **opts)
2491            join.set("on", on)
2492
2493        if using:
2494            join = _apply_list_builder(
2495                *ensure_collection(using),
2496                instance=join,
2497                arg="using",
2498                append=append,
2499                copy=copy,
2500                **opts,
2501            )
2502
2503        if join_alias:
2504            join.set("this", alias_(join.this, join_alias, table=True))
2505        return _apply_list_builder(
2506            join,
2507            instance=self,
2508            arg="joins",
2509            append=append,
2510            copy=copy,
2511            **opts,
2512        )
2513
2514    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2515        """
2516        Append to or set the WHERE expressions.
2517
2518        Example:
2519            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2520            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2521
2522        Args:
2523            *expressions (str | Expression): the SQL code strings to parse.
2524                If an `Expression` instance is passed, it will be used as-is.
2525                Multiple expressions are combined with an AND operator.
2526            append (bool): if `True`, AND the new expressions to any existing expression.
2527                Otherwise, this resets the expression.
2528            dialect (str): the dialect used to parse the input expressions.
2529            copy (bool): if `False`, modify this expression instance in-place.
2530            opts (kwargs): other options to use to parse the input expressions.
2531
2532        Returns:
2533            Select: the modified expression.
2534        """
2535        return _apply_conjunction_builder(
2536            *expressions,
2537            instance=self,
2538            arg="where",
2539            append=append,
2540            into=Where,
2541            dialect=dialect,
2542            copy=copy,
2543            **opts,
2544        )
2545
2546    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2547        """
2548        Append to or set the HAVING expressions.
2549
2550        Example:
2551            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2552            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2553
2554        Args:
2555            *expressions (str | Expression): the SQL code strings to parse.
2556                If an `Expression` instance is passed, it will be used as-is.
2557                Multiple expressions are combined with an AND operator.
2558            append (bool): if `True`, AND the new expressions to any existing expression.
2559                Otherwise, this resets the expression.
2560            dialect (str): the dialect used to parse the input expressions.
2561            copy (bool): if `False`, modify this expression instance in-place.
2562            opts (kwargs): other options to use to parse the input expressions.
2563
2564        Returns:
2565            Select: the modified expression.
2566        """
2567        return _apply_conjunction_builder(
2568            *expressions,
2569            instance=self,
2570            arg="having",
2571            append=append,
2572            into=Having,
2573            dialect=dialect,
2574            copy=copy,
2575            **opts,
2576        )
2577
2578    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2579        return _apply_list_builder(
2580            *expressions,
2581            instance=self,
2582            arg="windows",
2583            append=append,
2584            into=Window,
2585            dialect=dialect,
2586            copy=copy,
2587            **opts,
2588        )
2589
2590    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2591        return _apply_conjunction_builder(
2592            *expressions,
2593            instance=self,
2594            arg="qualify",
2595            append=append,
2596            into=Qualify,
2597            dialect=dialect,
2598            copy=copy,
2599            **opts,
2600        )
2601
2602    def distinct(self, distinct=True, copy=True) -> Select:
2603        """
2604        Set the OFFSET expression.
2605
2606        Example:
2607            >>> Select().from_("tbl").select("x").distinct().sql()
2608            'SELECT DISTINCT x FROM tbl'
2609
2610        Args:
2611            distinct (bool): whether the Select should be distinct
2612            copy (bool): if `False`, modify this expression instance in-place.
2613
2614        Returns:
2615            Select: the modified expression.
2616        """
2617        instance = _maybe_copy(self, copy)
2618        instance.set("distinct", Distinct() if distinct else None)
2619        return instance
2620
2621    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2622        """
2623        Convert this expression to a CREATE TABLE AS statement.
2624
2625        Example:
2626            >>> Select().select("*").from_("tbl").ctas("x").sql()
2627            'CREATE TABLE x AS SELECT * FROM tbl'
2628
2629        Args:
2630            table (str | Expression): the SQL code string to parse as the table name.
2631                If another `Expression` instance is passed, it will be used as-is.
2632            properties (dict): an optional mapping of table properties
2633            dialect (str): the dialect used to parse the input table.
2634            copy (bool): if `False`, modify this expression instance in-place.
2635            opts (kwargs): other options to use to parse the input table.
2636
2637        Returns:
2638            Create: the CREATE TABLE AS expression
2639        """
2640        instance = _maybe_copy(self, copy)
2641        table_expression = maybe_parse(
2642            table,
2643            into=Table,
2644            dialect=dialect,
2645            **opts,
2646        )
2647        properties_expression = None
2648        if properties:
2649            properties_expression = Properties.from_dict(properties)
2650
2651        return Create(
2652            this=table_expression,
2653            kind="table",
2654            expression=instance,
2655            properties=properties_expression,
2656        )
2657
2658    def lock(self, update: bool = True, copy: bool = True) -> Select:
2659        """
2660        Set the locking read mode for this expression.
2661
2662        Examples:
2663            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2664            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2665
2666            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2667            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2668
2669        Args:
2670            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2671            copy: if `False`, modify this expression instance in-place.
2672
2673        Returns:
2674            The modified expression.
2675        """
2676
2677        inst = _maybe_copy(self, copy)
2678        inst.set("lock", Lock(update=update))
2679
2680        return inst
2681
2682    @property
2683    def named_selects(self) -> t.List[str]:
2684        return [e.output_name for e in self.expressions if e.alias_or_name]
2685
2686    @property
2687    def is_star(self) -> bool:
2688        return any(expression.is_star for expression in self.expressions)
2689
2690    @property
2691    def selects(self) -> t.List[Expression]:
2692        return self.expressions
2693
2694
2695class Subquery(DerivedTable, Unionable):
2696    arg_types = {
2697        "this": True,
2698        "alias": False,
2699        "with": False,
2700        **QUERY_MODIFIERS,
2701    }
2702
2703    def unnest(self):
2704        """
2705        Returns the first non subquery.
2706        """
2707        expression = self
2708        while isinstance(expression, Subquery):
2709            expression = expression.this
2710        return expression
2711
2712    @property
2713    def is_star(self) -> bool:
2714        return self.this.is_star
2715
2716    @property
2717    def output_name(self):
2718        return self.alias
2719
2720
2721class TableSample(Expression):
2722    arg_types = {
2723        "this": False,
2724        "method": False,
2725        "bucket_numerator": False,
2726        "bucket_denominator": False,
2727        "bucket_field": False,
2728        "percent": False,
2729        "rows": False,
2730        "size": False,
2731        "seed": False,
2732        "kind": False,
2733    }
2734
2735
2736class Tag(Expression):
2737    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
2738
2739    arg_types = {
2740        "this": False,
2741        "prefix": False,
2742        "postfix": False,
2743    }
2744
2745
2746class Pivot(Expression):
2747    arg_types = {
2748        "this": False,
2749        "alias": False,
2750        "expressions": True,
2751        "field": True,
2752        "unpivot": True,
2753        "columns": False,
2754    }
2755
2756
2757class Window(Expression):
2758    arg_types = {
2759        "this": True,
2760        "partition_by": False,
2761        "order": False,
2762        "spec": False,
2763        "alias": False,
2764    }
2765
2766
2767class WindowSpec(Expression):
2768    arg_types = {
2769        "kind": False,
2770        "start": False,
2771        "start_side": False,
2772        "end": False,
2773        "end_side": False,
2774    }
2775
2776
2777class Where(Expression):
2778    pass
2779
2780
2781class Star(Expression):
2782    arg_types = {"except": False, "replace": False}
2783
2784    @property
2785    def name(self) -> str:
2786        return "*"
2787
2788    @property
2789    def output_name(self):
2790        return self.name
2791
2792
2793class Parameter(Expression):
2794    arg_types = {"this": True, "wrapped": False}
2795
2796
2797class SessionParameter(Expression):
2798    arg_types = {"this": True, "kind": False}
2799
2800
2801class Placeholder(Expression):
2802    arg_types = {"this": False}
2803
2804
2805class Null(Condition):
2806    arg_types: t.Dict[str, t.Any] = {}
2807
2808    @property
2809    def name(self) -> str:
2810        return "NULL"
2811
2812
2813class Boolean(Condition):
2814    pass
2815
2816
2817class DataType(Expression):
2818    arg_types = {
2819        "this": True,
2820        "expressions": False,
2821        "nested": False,
2822        "values": False,
2823        "prefix": False,
2824    }
2825
2826    class Type(AutoName):
2827        CHAR = auto()
2828        NCHAR = auto()
2829        VARCHAR = auto()
2830        NVARCHAR = auto()
2831        TEXT = auto()
2832        MEDIUMTEXT = auto()
2833        LONGTEXT = auto()
2834        MEDIUMBLOB = auto()
2835        LONGBLOB = auto()
2836        BINARY = auto()
2837        VARBINARY = auto()
2838        INT = auto()
2839        UINT = auto()
2840        TINYINT = auto()
2841        UTINYINT = auto()
2842        SMALLINT = auto()
2843        USMALLINT = auto()
2844        BIGINT = auto()
2845        UBIGINT = auto()
2846        FLOAT = auto()
2847        DOUBLE = auto()
2848        DECIMAL = auto()
2849        BIGDECIMAL = auto()
2850        BIT = auto()
2851        BOOLEAN = auto()
2852        JSON = auto()
2853        JSONB = auto()
2854        INTERVAL = auto()
2855        TIME = auto()
2856        TIMESTAMP = auto()
2857        TIMESTAMPTZ = auto()
2858        TIMESTAMPLTZ = auto()
2859        DATE = auto()
2860        DATETIME = auto()
2861        ARRAY = auto()
2862        MAP = auto()
2863        UUID = auto()
2864        GEOGRAPHY = auto()
2865        GEOMETRY = auto()
2866        STRUCT = auto()
2867        NULLABLE = auto()
2868        HLLSKETCH = auto()
2869        HSTORE = auto()
2870        SUPER = auto()
2871        SERIAL = auto()
2872        SMALLSERIAL = auto()
2873        BIGSERIAL = auto()
2874        XML = auto()
2875        UNIQUEIDENTIFIER = auto()
2876        MONEY = auto()
2877        SMALLMONEY = auto()
2878        ROWVERSION = auto()
2879        IMAGE = auto()
2880        VARIANT = auto()
2881        OBJECT = auto()
2882        INET = auto()
2883        NULL = auto()
2884        UNKNOWN = auto()  # Sentinel value, useful for type annotation
2885
2886    TEXT_TYPES = {
2887        Type.CHAR,
2888        Type.NCHAR,
2889        Type.VARCHAR,
2890        Type.NVARCHAR,
2891        Type.TEXT,
2892    }
2893
2894    INTEGER_TYPES = {
2895        Type.INT,
2896        Type.TINYINT,
2897        Type.SMALLINT,
2898        Type.BIGINT,
2899    }
2900
2901    FLOAT_TYPES = {
2902        Type.FLOAT,
2903        Type.DOUBLE,
2904    }
2905
2906    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
2907
2908    TEMPORAL_TYPES = {
2909        Type.TIMESTAMP,
2910        Type.TIMESTAMPTZ,
2911        Type.TIMESTAMPLTZ,
2912        Type.DATE,
2913        Type.DATETIME,
2914    }
2915
2916    @classmethod
2917    def build(
2918        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
2919    ) -> DataType:
2920        from sqlglot import parse_one
2921
2922        if isinstance(dtype, str):
2923            if dtype.upper() in cls.Type.__members__:
2924                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
2925            else:
2926                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
2927            if data_type_exp is None:
2928                raise ValueError(f"Unparsable data type value: {dtype}")
2929        elif isinstance(dtype, DataType.Type):
2930            data_type_exp = DataType(this=dtype)
2931        elif isinstance(dtype, DataType):
2932            return dtype
2933        else:
2934            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
2935        return DataType(**{**data_type_exp.args, **kwargs})
2936
2937    def is_type(self, dtype: DataType.Type) -> bool:
2938        return self.this == dtype
2939
2940
2941# https://www.postgresql.org/docs/15/datatype-pseudo.html
2942class PseudoType(Expression):
2943    pass
2944
2945
2946class StructKwarg(Expression):
2947    arg_types = {"this": True, "expression": True}
2948
2949
2950# WHERE x <OP> EXISTS|ALL|ANY|SOME(SELECT ...)
2951class SubqueryPredicate(Predicate):
2952    pass
2953
2954
2955class All(SubqueryPredicate):
2956    pass
2957
2958
2959class Any(SubqueryPredicate):
2960    pass
2961
2962
2963class Exists(SubqueryPredicate):
2964    pass
2965
2966
2967# Commands to interact with the databases or engines. For most of the command
2968# expressions we parse whatever comes after the command's name as a string.
2969class Command(Expression):
2970    arg_types = {"this": True, "expression": False}
2971
2972
2973class Transaction(Expression):
2974    arg_types = {"this": False, "modes": False}
2975
2976
2977class Commit(Expression):
2978    arg_types = {"chain": False}
2979
2980
2981class Rollback(Expression):
2982    arg_types = {"savepoint": False}
2983
2984
2985class AlterTable(Expression):
2986    arg_types = {"this": True, "actions": True, "exists": False}
2987
2988
2989class AddConstraint(Expression):
2990    arg_types = {"this": False, "expression": False, "enforced": False}
2991
2992
2993class DropPartition(Expression):
2994    arg_types = {"expressions": True, "exists": False}
2995
2996
2997# Binary expressions like (ADD a b)
2998class Binary(Expression):
2999    arg_types = {"this": True, "expression": True}
3000
3001    @property
3002    def left(self):
3003        return self.this
3004
3005    @property
3006    def right(self):
3007        return self.expression
3008
3009
3010class Add(Binary):
3011    pass
3012
3013
3014class Connector(Binary, Condition):
3015    pass
3016
3017
3018class And(Connector):
3019    pass
3020
3021
3022class Or(Connector):
3023    pass
3024
3025
3026class BitwiseAnd(Binary):
3027    pass
3028
3029
3030class BitwiseLeftShift(Binary):
3031    pass
3032
3033
3034class BitwiseOr(Binary):
3035    pass
3036
3037
3038class BitwiseRightShift(Binary):
3039    pass
3040
3041
3042class BitwiseXor(Binary):
3043    pass
3044
3045
3046class Div(Binary):
3047    pass
3048
3049
3050class Overlaps(Binary):
3051    pass
3052
3053
3054class Dot(Binary):
3055    @property
3056    def name(self) -> str:
3057        return self.expression.name
3058
3059    @classmethod
3060    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3061        """Build a Dot object with a sequence of expressions."""
3062        if len(expressions) < 2:
3063            raise ValueError(f"Dot requires >= 2 expressions.")
3064
3065        a, b, *expressions = expressions
3066        dot = Dot(this=a, expression=b)
3067
3068        for expression in expressions:
3069            dot = Dot(this=dot, expression=expression)
3070
3071        return dot
3072
3073
3074class DPipe(Binary):
3075    pass
3076
3077
3078class EQ(Binary, Predicate):
3079    pass
3080
3081
3082class NullSafeEQ(Binary, Predicate):
3083    pass
3084
3085
3086class NullSafeNEQ(Binary, Predicate):
3087    pass
3088
3089
3090class Distance(Binary):
3091    pass
3092
3093
3094class Escape(Binary):
3095    pass
3096
3097
3098class Glob(Binary, Predicate):
3099    pass
3100
3101
3102class GT(Binary, Predicate):
3103    pass
3104
3105
3106class GTE(Binary, Predicate):
3107    pass
3108
3109
3110class ILike(Binary, Predicate):
3111    pass
3112
3113
3114class ILikeAny(Binary, Predicate):
3115    pass
3116
3117
3118class IntDiv(Binary):
3119    pass
3120
3121
3122class Is(Binary, Predicate):
3123    pass
3124
3125
3126class Kwarg(Binary):
3127    """Kwarg in special functions like func(kwarg => y)."""
3128
3129
3130class Like(Binary, Predicate):
3131    pass
3132
3133
3134class LikeAny(Binary, Predicate):
3135    pass
3136
3137
3138class LT(Binary, Predicate):
3139    pass
3140
3141
3142class LTE(Binary, Predicate):
3143    pass
3144
3145
3146class Mod(Binary):
3147    pass
3148
3149
3150class Mul(Binary):
3151    pass
3152
3153
3154class NEQ(Binary, Predicate):
3155    pass
3156
3157
3158class SimilarTo(Binary, Predicate):
3159    pass
3160
3161
3162class Slice(Binary):
3163    arg_types = {"this": False, "expression": False}
3164
3165
3166class Sub(Binary):
3167    pass
3168
3169
3170class ArrayOverlaps(Binary):
3171    pass
3172
3173
3174# Unary Expressions
3175# (NOT a)
3176class Unary(Expression):
3177    pass
3178
3179
3180class BitwiseNot(Unary):
3181    pass
3182
3183
3184class Not(Unary, Condition):
3185    pass
3186
3187
3188class Paren(Unary, Condition):
3189    arg_types = {"this": True, "with": False}
3190
3191
3192class Neg(Unary):
3193    pass
3194
3195
3196class Alias(Expression):
3197    arg_types = {"this": True, "alias": False}
3198
3199    @property
3200    def output_name(self):
3201        return self.alias
3202
3203
3204class Aliases(Expression):
3205    arg_types = {"this": True, "expressions": True}
3206
3207    @property
3208    def aliases(self):
3209        return self.expressions
3210
3211
3212class AtTimeZone(Expression):
3213    arg_types = {"this": True, "zone": True}
3214
3215
3216class Between(Predicate):
3217    arg_types = {"this": True, "low": True, "high": True}
3218
3219
3220class Bracket(Condition):
3221    arg_types = {"this": True, "expressions": True}
3222
3223
3224class Distinct(Expression):
3225    arg_types = {"expressions": False, "on": False}
3226
3227
3228class In(Predicate):
3229    arg_types = {
3230        "this": True,
3231        "expressions": False,
3232        "query": False,
3233        "unnest": False,
3234        "field": False,
3235        "is_global": False,
3236    }
3237
3238
3239class TimeUnit(Expression):
3240    """Automatically converts unit arg into a var."""
3241
3242    arg_types = {"unit": False}
3243
3244    def __init__(self, **args):
3245        unit = args.get("unit")
3246        if isinstance(unit, (Column, Literal)):
3247            args["unit"] = Var(this=unit.name)
3248        elif isinstance(unit, Week):
3249            unit.set("this", Var(this=unit.this.name))
3250        super().__init__(**args)
3251
3252
3253class Interval(TimeUnit):
3254    arg_types = {"this": False, "unit": False}
3255
3256
3257class IgnoreNulls(Expression):
3258    pass
3259
3260
3261class RespectNulls(Expression):
3262    pass
3263
3264
3265# Functions
3266class Func(Condition):
3267    """
3268    The base class for all function expressions.
3269
3270    Attributes:
3271        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3272            treated as a variable length argument and the argument's value will be stored as a list.
3273        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3274            for this function expression. These values are used to map this node to a name during parsing
3275            as well as to provide the function's name during SQL string generation. By default the SQL
3276            name is set to the expression's class name transformed to snake case.
3277    """
3278
3279    is_var_len_args = False
3280
3281    @classmethod
3282    def from_arg_list(cls, args):
3283        if cls.is_var_len_args:
3284            all_arg_keys = list(cls.arg_types)
3285            # If this function supports variable length argument treat the last argument as such.
3286            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3287            num_non_var = len(non_var_len_arg_keys)
3288
3289            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3290            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3291        else:
3292            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3293
3294        return cls(**args_dict)
3295
3296    @classmethod
3297    def sql_names(cls):
3298        if cls is Func:
3299            raise NotImplementedError(
3300                "SQL name is only supported by concrete function implementations"
3301            )
3302        if "_sql_names" not in cls.__dict__:
3303            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3304        return cls._sql_names
3305
3306    @classmethod
3307    def sql_name(cls):
3308        return cls.sql_names()[0]
3309
3310    @classmethod
3311    def default_parser_mappings(cls):
3312        return {name: cls.from_arg_list for name in cls.sql_names()}
3313
3314
3315class AggFunc(Func):
3316    pass
3317
3318
3319class Abs(Func):
3320    pass
3321
3322
3323class Anonymous(Func):
3324    arg_types = {"this": True, "expressions": False}
3325    is_var_len_args = True
3326
3327
3328# https://docs.snowflake.com/en/sql-reference/functions/hll
3329# https://docs.aws.amazon.com/redshift/latest/dg/r_HLL_function.html
3330class Hll(AggFunc):
3331    arg_types = {"this": True, "expressions": False}
3332    is_var_len_args = True
3333
3334
3335class ApproxDistinct(AggFunc):
3336    arg_types = {"this": True, "accuracy": False}
3337
3338
3339class Array(Func):
3340    arg_types = {"expressions": False}
3341    is_var_len_args = True
3342
3343
3344# https://docs.snowflake.com/en/sql-reference/functions/to_char
3345class ToChar(Func):
3346    arg_types = {"this": True, "format": False}
3347
3348
3349class GenerateSeries(Func):
3350    arg_types = {"start": True, "end": True, "step": False}
3351
3352
3353class ArrayAgg(AggFunc):
3354    pass
3355
3356
3357class ArrayAll(Func):
3358    arg_types = {"this": True, "expression": True}
3359
3360
3361class ArrayAny(Func):
3362    arg_types = {"this": True, "expression": True}
3363
3364
3365class ArrayConcat(Func):
3366    arg_types = {"this": True, "expressions": False}
3367    is_var_len_args = True
3368
3369
3370class ArrayContains(Binary, Func):
3371    pass
3372
3373
3374class ArrayContained(Binary):
3375    pass
3376
3377
3378class ArrayFilter(Func):
3379    arg_types = {"this": True, "expression": True}
3380    _sql_names = ["FILTER", "ARRAY_FILTER"]
3381
3382
3383class ArrayJoin(Func):
3384    arg_types = {"this": True, "expression": True, "null": False}
3385
3386
3387class ArraySize(Func):
3388    arg_types = {"this": True, "expression": False}
3389
3390
3391class ArraySort(Func):
3392    arg_types = {"this": True, "expression": False}
3393
3394
3395class ArraySum(Func):
3396    pass
3397
3398
3399class ArrayUnionAgg(AggFunc):
3400    pass
3401
3402
3403class Avg(AggFunc):
3404    pass
3405
3406
3407class AnyValue(AggFunc):
3408    pass
3409
3410
3411class Case(Func):
3412    arg_types = {"this": False, "ifs": True, "default": False}
3413
3414
3415class Cast(Func):
3416    arg_types = {"this": True, "to": True}
3417
3418    @property
3419    def name(self) -> str:
3420        return self.this.name
3421
3422    @property
3423    def to(self):
3424        return self.args["to"]
3425
3426    @property
3427    def output_name(self):
3428        return self.name
3429
3430    def is_type(self, dtype: DataType.Type) -> bool:
3431        return self.to.is_type(dtype)
3432
3433
3434class Collate(Binary):
3435    pass
3436
3437
3438class TryCast(Cast):
3439    pass
3440
3441
3442class Ceil(Func):
3443    arg_types = {"this": True, "decimals": False}
3444    _sql_names = ["CEIL", "CEILING"]
3445
3446
3447class Coalesce(Func):
3448    arg_types = {"this": True, "expressions": False}
3449    is_var_len_args = True
3450
3451
3452class Concat(Func):
3453    arg_types = {"expressions": True}
3454    is_var_len_args = True
3455
3456
3457class ConcatWs(Concat):
3458    _sql_names = ["CONCAT_WS"]
3459
3460
3461class Count(AggFunc):
3462    arg_types = {"this": False}
3463
3464
3465class CountIf(AggFunc):
3466    pass
3467
3468
3469class CurrentDate(Func):
3470    arg_types = {"this": False}
3471
3472
3473class CurrentDatetime(Func):
3474    arg_types = {"this": False}
3475
3476
3477class CurrentTime(Func):
3478    arg_types = {"this": False}
3479
3480
3481class CurrentTimestamp(Func):
3482    arg_types = {"this": False}
3483
3484
3485class CurrentUser(Func):
3486    arg_types = {"this": False}
3487
3488
3489class DateAdd(Func, TimeUnit):
3490    arg_types = {"this": True, "expression": True, "unit": False}
3491
3492
3493class DateSub(Func, TimeUnit):
3494    arg_types = {"this": True, "expression": True, "unit": False}
3495
3496
3497class DateDiff(Func, TimeUnit):
3498    _sql_names = ["DATEDIFF", "DATE_DIFF"]
3499    arg_types = {"this": True, "expression": True, "unit": False}
3500
3501
3502class DateTrunc(Func):
3503    arg_types = {"unit": True, "this": True, "zone": False}
3504
3505
3506class DatetimeAdd(Func, TimeUnit):
3507    arg_types = {"this": True, "expression": True, "unit": False}
3508
3509
3510class DatetimeSub(Func, TimeUnit):
3511    arg_types = {"this": True, "expression": True, "unit": False}
3512
3513
3514class DatetimeDiff(Func, TimeUnit):
3515    arg_types = {"this": True, "expression": True, "unit": False}
3516
3517
3518class DatetimeTrunc(Func, TimeUnit):
3519    arg_types = {"this": True, "unit": True, "zone": False}
3520
3521
3522class DayOfWeek(Func):
3523    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
3524
3525
3526class DayOfMonth(Func):
3527    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
3528
3529
3530class DayOfYear(Func):
3531    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
3532
3533
3534class WeekOfYear(Func):
3535    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
3536
3537
3538class LastDateOfMonth(Func):
3539    pass
3540
3541
3542class Extract(Func):
3543    arg_types = {"this": True, "expression": True}
3544
3545
3546class TimestampAdd(Func, TimeUnit):
3547    arg_types = {"this": True, "expression": True, "unit": False}
3548
3549
3550class TimestampSub(Func, TimeUnit):
3551    arg_types = {"this": True, "expression": True, "unit": False}
3552
3553
3554class TimestampDiff(Func, TimeUnit):
3555    arg_types = {"this": True, "expression": True, "unit": False}
3556
3557
3558class TimestampTrunc(Func, TimeUnit):
3559    arg_types = {"this": True, "unit": True, "zone": False}
3560
3561
3562class TimeAdd(Func, TimeUnit):
3563    arg_types = {"this": True, "expression": True, "unit": False}
3564
3565
3566class TimeSub(Func, TimeUnit):
3567    arg_types = {"this": True, "expression": True, "unit": False}
3568
3569
3570class TimeDiff(Func, TimeUnit):
3571    arg_types = {"this": True, "expression": True, "unit": False}
3572
3573
3574class TimeTrunc(Func, TimeUnit):
3575    arg_types = {"this": True, "unit": True, "zone": False}
3576
3577
3578class DateFromParts(Func):
3579    _sql_names = ["DATEFROMPARTS"]
3580    arg_types = {"year": True, "month": True, "day": True}
3581
3582
3583class DateStrToDate(Func):
3584    pass
3585
3586
3587class DateToDateStr(Func):
3588    pass
3589
3590
3591class DateToDi(Func):
3592    pass
3593
3594
3595class Day(Func):
3596    pass
3597
3598
3599class Decode(Func):
3600    arg_types = {"this": True, "charset": True, "replace": False}
3601
3602
3603class DiToDate(Func):
3604    pass
3605
3606
3607class Encode(Func):
3608    arg_types = {"this": True, "charset": True}
3609
3610
3611class Exp(Func):
3612    pass
3613
3614
3615class Explode(Func):
3616    pass
3617
3618
3619class ExponentialTimeDecayedAvg(AggFunc):
3620    arg_types = {"this": True, "time": False, "decay": False}
3621
3622
3623class Floor(Func):
3624    arg_types = {"this": True, "decimals": False}
3625
3626
3627class Greatest(Func):
3628    arg_types = {"this": True, "expressions": False}
3629    is_var_len_args = True
3630
3631
3632class GroupConcat(Func):
3633    arg_types = {"this": True, "separator": False}
3634
3635
3636class GroupUniqArray(AggFunc):
3637    arg_types = {"this": True, "size": False}
3638
3639
3640class Hex(Func):
3641    pass
3642
3643
3644class Histogram(AggFunc):
3645    arg_types = {"this": True, "bins": False}
3646
3647
3648class If(Func):
3649    arg_types = {"this": True, "true": True, "false": False}
3650
3651
3652class IfNull(Func):
3653    arg_types = {"this": True, "expression": False}
3654    _sql_names = ["IFNULL", "NVL"]
3655
3656
3657class Initcap(Func):
3658    pass
3659
3660
3661class JSONKeyValue(Expression):
3662    arg_types = {"this": True, "expression": True}
3663
3664
3665class JSONObject(Func):
3666    arg_types = {
3667        "expressions": False,
3668        "null_handling": False,
3669        "unique_keys": False,
3670        "return_type": False,
3671        "format_json": False,
3672        "encoding": False,
3673    }
3674
3675
3676class JSONBContains(Binary):
3677    _sql_names = ["JSONB_CONTAINS"]
3678
3679
3680class JSONExtract(Binary, Func):
3681    _sql_names = ["JSON_EXTRACT"]
3682
3683
3684class JSONExtractScalar(JSONExtract):
3685    _sql_names = ["JSON_EXTRACT_SCALAR"]
3686
3687
3688class JSONBExtract(JSONExtract):
3689    _sql_names = ["JSONB_EXTRACT"]
3690
3691
3692class JSONBExtractScalar(JSONExtract):
3693    _sql_names = ["JSONB_EXTRACT_SCALAR"]
3694
3695
3696class JSONFormat(Func):
3697    arg_types = {"this": False, "options": False}
3698    _sql_names = ["JSON_FORMAT"]
3699
3700
3701class Least(Func):
3702    arg_types = {"expressions": False}
3703    is_var_len_args = True
3704
3705
3706class Length(Func):
3707    pass
3708
3709
3710class Levenshtein(Func):
3711    arg_types = {
3712        "this": True,
3713        "expression": False,
3714        "ins_cost": False,
3715        "del_cost": False,
3716        "sub_cost": False,
3717    }
3718
3719
3720class Ln(Func):
3721    pass
3722
3723
3724class Log(Func):
3725    arg_types = {"this": True, "expression": False}
3726
3727
3728class Log2(Func):
3729    pass
3730
3731
3732class Log10(Func):
3733    pass
3734
3735
3736class LogicalOr(AggFunc):
3737    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
3738
3739
3740class LogicalAnd(AggFunc):
3741    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
3742
3743
3744class Lower(Func):
3745    _sql_names = ["LOWER", "LCASE"]
3746
3747
3748class Map(Func):
3749    arg_types = {"keys": False, "values": False}
3750
3751
3752class StarMap(Func):
3753    pass
3754
3755
3756class VarMap(Func):
3757    arg_types = {"keys": True, "values": True}
3758    is_var_len_args = True
3759
3760
3761# https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html
3762class MatchAgainst(Func):
3763    arg_types = {"this": True, "expressions": True, "modifier": False}
3764
3765
3766class Max(AggFunc):
3767    arg_types = {"this": True, "expressions": False}
3768    is_var_len_args = True
3769
3770
3771class Min(AggFunc):
3772    arg_types = {"this": True, "expressions": False}
3773    is_var_len_args = True
3774
3775
3776class Month(Func):
3777    pass
3778
3779
3780class Nvl2(Func):
3781    arg_types = {"this": True, "true": True, "false": False}
3782
3783
3784class Posexplode(Func):
3785    pass
3786
3787
3788class Pow(Binary, Func):
3789    _sql_names = ["POWER", "POW"]
3790
3791
3792class PercentileCont(AggFunc):
3793    pass
3794
3795
3796class PercentileDisc(AggFunc):
3797    pass
3798
3799
3800class Quantile(AggFunc):
3801    arg_types = {"this": True, "quantile": True}
3802
3803
3804# Clickhouse-specific:
3805# https://clickhouse.com/docs/en/sql-reference/aggregate-functions/reference/quantiles/#quantiles
3806class Quantiles(AggFunc):
3807    arg_types = {"parameters": True, "expressions": True}
3808    is_var_len_args = True
3809
3810
3811class QuantileIf(AggFunc):
3812    arg_types = {"parameters": True, "expressions": True}
3813
3814
3815class ApproxQuantile(Quantile):
3816    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
3817
3818
3819class RangeN(Func):
3820    arg_types = {"this": True, "expressions": True, "each": False}
3821
3822
3823class ReadCSV(Func):
3824    _sql_names = ["READ_CSV"]
3825    is_var_len_args = True
3826    arg_types = {"this": True, "expressions": False}
3827
3828
3829class Reduce(Func):
3830    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
3831
3832
3833class RegexpExtract(Func):
3834    arg_types = {
3835        "this": True,
3836        "expression": True,
3837        "position": False,
3838        "occurrence": False,
3839        "group": False,
3840    }
3841
3842
3843class RegexpLike(Func):
3844    arg_types = {"this": True, "expression": True, "flag": False}
3845
3846
3847class RegexpILike(Func):
3848    arg_types = {"this": True, "expression": True, "flag": False}
3849
3850
3851# https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.split.html
3852# limit is the number of times a pattern is applied
3853class RegexpSplit(Func):
3854    arg_types = {"this": True, "expression": True, "limit": False}
3855
3856
3857class Repeat(Func):
3858    arg_types = {"this": True, "times": True}
3859
3860
3861class Round(Func):
3862    arg_types = {"this": True, "decimals": False}
3863
3864
3865class RowNumber(Func):
3866    arg_types: t.Dict[str, t.Any] = {}
3867
3868
3869class SafeDivide(Func):
3870    arg_types = {"this": True, "expression": True}
3871
3872
3873class SetAgg(AggFunc):
3874    pass
3875
3876
3877class SortArray(Func):
3878    arg_types = {"this": True, "asc": False}
3879
3880
3881class Split(Func):
3882    arg_types = {"this": True, "expression": True, "limit": False}
3883
3884
3885# Start may be omitted in the case of postgres
3886# https://www.postgresql.org/docs/9.1/functions-string.html @ Table 9-6
3887class Substring(Func):
3888    arg_types = {"this": True, "start": False, "length": False}
3889
3890
3891class StrPosition(Func):
3892    arg_types = {
3893        "this": True,
3894        "substr": True,
3895        "position": False,
3896        "instance": False,
3897    }
3898
3899
3900class StrToDate(Func):
3901    arg_types = {"this": True, "format": True}
3902
3903
3904class StrToTime(Func):
3905    arg_types = {"this": True, "format": True}
3906
3907
3908# Spark allows unix_timestamp()
3909# https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.unix_timestamp.html
3910class StrToUnix(Func):
3911    arg_types = {"this": False, "format": False}
3912
3913
3914class NumberToStr(Func):
3915    arg_types = {"this": True, "format": True}
3916
3917
3918class Struct(Func):
3919    arg_types = {"expressions": True}
3920    is_var_len_args = True
3921
3922
3923class StructExtract(Func):
3924    arg_types = {"this": True, "expression": True}
3925
3926
3927class Sum(AggFunc):
3928    pass
3929
3930
3931class Sqrt(Func):
3932    pass
3933
3934
3935class Stddev(AggFunc):
3936    pass
3937
3938
3939class StddevPop(AggFunc):
3940    pass
3941
3942
3943class StddevSamp(AggFunc):
3944    pass
3945
3946
3947class TimeToStr(Func):
3948    arg_types = {"this": True, "format": True}
3949
3950
3951class TimeToTimeStr(Func):
3952    pass
3953
3954
3955class TimeToUnix(Func):
3956    pass
3957
3958
3959class TimeStrToDate(Func):
3960    pass
3961
3962
3963class TimeStrToTime(Func):
3964    pass
3965
3966
3967class TimeStrToUnix(Func):
3968    pass
3969
3970
3971class Trim(Func):
3972    arg_types = {
3973        "this": True,
3974        "expression": False,
3975        "position": False,
3976        "collation": False,
3977    }
3978
3979
3980class TsOrDsAdd(Func, TimeUnit):
3981    arg_types = {"this": True, "expression": True, "unit": False}
3982
3983
3984class TsOrDsToDateStr(Func):
3985    pass
3986
3987
3988class TsOrDsToDate(Func):
3989    arg_types = {"this": True, "format": False}
3990
3991
3992class TsOrDiToDi(Func):
3993    pass
3994
3995
3996class Unhex(Func):
3997    pass
3998
3999
4000class UnixToStr(Func):
4001    arg_types = {"this": True, "format": False}
4002
4003
4004# https://prestodb.io/docs/current/functions/datetime.html
4005# presto has weird zone/hours/minutes
4006class UnixToTime(Func):
4007    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4008
4009    SECONDS = Literal.string("seconds")
4010    MILLIS = Literal.string("millis")
4011    MICROS = Literal.string("micros")
4012
4013
4014class UnixToTimeStr(Func):
4015    pass
4016
4017
4018class Upper(Func):
4019    _sql_names = ["UPPER", "UCASE"]
4020
4021
4022class Variance(AggFunc):
4023    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
4024
4025
4026class VariancePop(AggFunc):
4027    _sql_names = ["VARIANCE_POP", "VAR_POP"]
4028
4029
4030class Week(Func):
4031    arg_types = {"this": True, "mode": False}
4032
4033
4034class XMLTable(Func):
4035    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
4036
4037
4038class Year(Func):
4039    pass
4040
4041
4042class Use(Expression):
4043    arg_types = {"this": True, "kind": False}
4044
4045
4046class Merge(Expression):
4047    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
4048
4049
4050class When(Func):
4051    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
4052
4053
4054def _norm_arg(arg):
4055    return arg.lower() if type(arg) is str else arg
4056
4057
4058ALL_FUNCTIONS = subclasses(__name__, Func, (AggFunc, Anonymous, Func))
4059
4060
4061# Helpers
4062@t.overload
4063def maybe_parse(
4064    sql_or_expression: ExpOrStr,
4065    *,
4066    into: t.Type[E],
4067    dialect: DialectType = None,
4068    prefix: t.Optional[str] = None,
4069    copy: bool = False,
4070    **opts,
4071) -> E:
4072    ...
4073
4074
4075@t.overload
4076def maybe_parse(
4077    sql_or_expression: str | E,
4078    *,
4079    into: t.Optional[IntoType] = None,
4080    dialect: DialectType = None,
4081    prefix: t.Optional[str] = None,
4082    copy: bool = False,
4083    **opts,
4084) -> E:
4085    ...
4086
4087
4088def maybe_parse(
4089    sql_or_expression: ExpOrStr,
4090    *,
4091    into: t.Optional[IntoType] = None,
4092    dialect: DialectType = None,
4093    prefix: t.Optional[str] = None,
4094    copy: bool = False,
4095    **opts,
4096) -> Expression:
4097    """Gracefully handle a possible string or expression.
4098
4099    Example:
4100        >>> maybe_parse("1")
4101        (LITERAL this: 1, is_string: False)
4102        >>> maybe_parse(to_identifier("x"))
4103        (IDENTIFIER this: x, quoted: False)
4104
4105    Args:
4106        sql_or_expression: the SQL code string or an expression
4107        into: the SQLGlot Expression to parse into
4108        dialect: the dialect used to parse the input expressions (in the case that an
4109            input expression is a SQL string).
4110        prefix: a string to prefix the sql with before it gets parsed
4111            (automatically includes a space)
4112        copy: whether or not to copy the expression.
4113        **opts: other options to use to parse the input expressions (again, in the case
4114            that an input expression is a SQL string).
4115
4116    Returns:
4117        Expression: the parsed or given expression.
4118    """
4119    if isinstance(sql_or_expression, Expression):
4120        if copy:
4121            return sql_or_expression.copy()
4122        return sql_or_expression
4123
4124    import sqlglot
4125
4126    sql = str(sql_or_expression)
4127    if prefix:
4128        sql = f"{prefix} {sql}"
4129    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)
4130
4131
4132def _maybe_copy(instance, copy=True):
4133    return instance.copy() if copy else instance
4134
4135
4136def _is_wrong_expression(expression, into):
4137    return isinstance(expression, Expression) and not isinstance(expression, into)
4138
4139
4140def _apply_builder(
4141    expression,
4142    instance,
4143    arg,
4144    copy=True,
4145    prefix=None,
4146    into=None,
4147    dialect=None,
4148    **opts,
4149):
4150    if _is_wrong_expression(expression, into):
4151        expression = into(this=expression)
4152    instance = _maybe_copy(instance, copy)
4153    expression = maybe_parse(
4154        sql_or_expression=expression,
4155        prefix=prefix,
4156        into=into,
4157        dialect=dialect,
4158        **opts,
4159    )
4160    instance.set(arg, expression)
4161    return instance
4162
4163
4164def _apply_child_list_builder(
4165    *expressions,
4166    instance,
4167    arg,
4168    append=True,
4169    copy=True,
4170    prefix=None,
4171    into=None,
4172    dialect=None,
4173    properties=None,
4174    **opts,
4175):
4176    instance = _maybe_copy(instance, copy)
4177    parsed = []
4178    for expression in expressions:
4179        if _is_wrong_expression(expression, into):
4180            expression = into(expressions=[expression])
4181        expression = maybe_parse(
4182            expression,
4183            into=into,
4184            dialect=dialect,
4185            prefix=prefix,
4186            **opts,
4187        )
4188        parsed.extend(expression.expressions)
4189
4190    existing = instance.args.get(arg)
4191    if append and existing:
4192        parsed = existing.expressions + parsed
4193
4194    child = into(expressions=parsed)
4195    for k, v in (properties or {}).items():
4196        child.set(k, v)
4197    instance.set(arg, child)
4198    return instance
4199
4200
4201def _apply_list_builder(
4202    *expressions,
4203    instance,
4204    arg,
4205    append=True,
4206    copy=True,
4207    prefix=None,
4208    into=None,
4209    dialect=None,
4210    **opts,
4211):
4212    inst = _maybe_copy(instance, copy)
4213
4214    expressions = [
4215        maybe_parse(
4216            sql_or_expression=expression,
4217            into=into,
4218            prefix=prefix,
4219            dialect=dialect,
4220            **opts,
4221        )
4222        for expression in expressions
4223    ]
4224
4225    existing_expressions = inst.args.get(arg)
4226    if append and existing_expressions:
4227        expressions = existing_expressions + expressions
4228
4229    inst.set(arg, expressions)
4230    return inst
4231
4232
4233def _apply_conjunction_builder(
4234    *expressions,
4235    instance,
4236    arg,
4237    into=None,
4238    append=True,
4239    copy=True,
4240    dialect=None,
4241    **opts,
4242):
4243    expressions = [exp for exp in expressions if exp is not None and exp != ""]
4244    if not expressions:
4245        return instance
4246
4247    inst = _maybe_copy(instance, copy)
4248
4249    existing = inst.args.get(arg)
4250    if append and existing is not None:
4251        expressions = [existing.this if into else existing] + list(expressions)
4252
4253    node = and_(*expressions, dialect=dialect, **opts)
4254
4255    inst.set(arg, into(this=node) if into else node)
4256    return inst
4257
4258
4259def _combine(expressions, operator, dialect=None, **opts):
4260    expressions = [condition(expression, dialect=dialect, **opts) for expression in expressions]
4261    this = expressions[0]
4262    if expressions[1:]:
4263        this = _wrap_operator(this)
4264    for expression in expressions[1:]:
4265        this = operator(this=this, expression=_wrap_operator(expression))
4266    return this
4267
4268
4269def _wrap_operator(expression):
4270    if isinstance(expression, (And, Or, Not)):
4271        expression = Paren(this=expression)
4272    return expression
4273
4274
4275def union(left, right, distinct=True, dialect=None, **opts):
4276    """
4277    Initializes a syntax tree from one UNION expression.
4278
4279    Example:
4280        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4281        'SELECT * FROM foo UNION SELECT * FROM bla'
4282
4283    Args:
4284        left (str | Expression): the SQL code string corresponding to the left-hand side.
4285            If an `Expression` instance is passed, it will be used as-is.
4286        right (str | Expression): the SQL code string corresponding to the right-hand side.
4287            If an `Expression` instance is passed, it will be used as-is.
4288        distinct (bool): set the DISTINCT flag if and only if this is true.
4289        dialect (str): the dialect used to parse the input expression.
4290        opts (kwargs): other options to use to parse the input expressions.
4291    Returns:
4292        Union: the syntax tree for the UNION expression.
4293    """
4294    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4295    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4296
4297    return Union(this=left, expression=right, distinct=distinct)
4298
4299
4300def intersect(left, right, distinct=True, dialect=None, **opts):
4301    """
4302    Initializes a syntax tree from one INTERSECT expression.
4303
4304    Example:
4305        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4306        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4307
4308    Args:
4309        left (str | Expression): the SQL code string corresponding to the left-hand side.
4310            If an `Expression` instance is passed, it will be used as-is.
4311        right (str | Expression): the SQL code string corresponding to the right-hand side.
4312            If an `Expression` instance is passed, it will be used as-is.
4313        distinct (bool): set the DISTINCT flag if and only if this is true.
4314        dialect (str): the dialect used to parse the input expression.
4315        opts (kwargs): other options to use to parse the input expressions.
4316    Returns:
4317        Intersect: the syntax tree for the INTERSECT expression.
4318    """
4319    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4320    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4321
4322    return Intersect(this=left, expression=right, distinct=distinct)
4323
4324
4325def except_(left, right, distinct=True, dialect=None, **opts):
4326    """
4327    Initializes a syntax tree from one EXCEPT expression.
4328
4329    Example:
4330        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4331        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4332
4333    Args:
4334        left (str | Expression): the SQL code string corresponding to the left-hand side.
4335            If an `Expression` instance is passed, it will be used as-is.
4336        right (str | Expression): the SQL code string corresponding to the right-hand side.
4337            If an `Expression` instance is passed, it will be used as-is.
4338        distinct (bool): set the DISTINCT flag if and only if this is true.
4339        dialect (str): the dialect used to parse the input expression.
4340        opts (kwargs): other options to use to parse the input expressions.
4341    Returns:
4342        Except: the syntax tree for the EXCEPT statement.
4343    """
4344    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4345    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4346
4347    return Except(this=left, expression=right, distinct=distinct)
4348
4349
4350def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4351    """
4352    Initializes a syntax tree from one or multiple SELECT expressions.
4353
4354    Example:
4355        >>> select("col1", "col2").from_("tbl").sql()
4356        'SELECT col1, col2 FROM tbl'
4357
4358    Args:
4359        *expressions: the SQL code string to parse as the expressions of a
4360            SELECT statement. If an Expression instance is passed, this is used as-is.
4361        dialect: the dialect used to parse the input expressions (in the case that an
4362            input expression is a SQL string).
4363        **opts: other options to use to parse the input expressions (again, in the case
4364            that an input expression is a SQL string).
4365
4366    Returns:
4367        Select: the syntax tree for the SELECT statement.
4368    """
4369    return Select().select(*expressions, dialect=dialect, **opts)
4370
4371
4372def from_(*expressions, dialect=None, **opts) -> Select:
4373    """
4374    Initializes a syntax tree from a FROM expression.
4375
4376    Example:
4377        >>> from_("tbl").select("col1", "col2").sql()
4378        'SELECT col1, col2 FROM tbl'
4379
4380    Args:
4381        *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a
4382            SELECT statement. If an Expression instance is passed, this is used as-is.
4383        dialect (str): the dialect used to parse the input expression (in the case that the
4384            input expression is a SQL string).
4385        **opts: other options to use to parse the input expressions (again, in the case
4386            that the input expression is a SQL string).
4387
4388    Returns:
4389        Select: the syntax tree for the SELECT statement.
4390    """
4391    return Select().from_(*expressions, dialect=dialect, **opts)
4392
4393
4394def update(
4395    table: str | Table,
4396    properties: dict,
4397    where: t.Optional[ExpOrStr] = None,
4398    from_: t.Optional[ExpOrStr] = None,
4399    dialect: DialectType = None,
4400    **opts,
4401) -> Update:
4402    """
4403    Creates an update statement.
4404
4405    Example:
4406        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
4407        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
4408
4409    Args:
4410        *properties: dictionary of properties to set which are
4411            auto converted to sql objects eg None -> NULL
4412        where: sql conditional parsed into a WHERE statement
4413        from_: sql statement parsed into a FROM statement
4414        dialect: the dialect used to parse the input expressions.
4415        **opts: other options to use to parse the input expressions.
4416
4417    Returns:
4418        Update: the syntax tree for the UPDATE statement.
4419    """
4420    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
4421    update_expr.set(
4422        "expressions",
4423        [
4424            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
4425            for k, v in properties.items()
4426        ],
4427    )
4428    if from_:
4429        update_expr.set(
4430            "from",
4431            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
4432        )
4433    if isinstance(where, Condition):
4434        where = Where(this=where)
4435    if where:
4436        update_expr.set(
4437            "where",
4438            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
4439        )
4440    return update_expr
4441
4442
4443def delete(
4444    table: ExpOrStr,
4445    where: t.Optional[ExpOrStr] = None,
4446    returning: t.Optional[ExpOrStr] = None,
4447    dialect: DialectType = None,
4448    **opts,
4449) -> Delete:
4450    """
4451    Builds a delete statement.
4452
4453    Example:
4454        >>> delete("my_table", where="id > 1").sql()
4455        'DELETE FROM my_table WHERE id > 1'
4456
4457    Args:
4458        where: sql conditional parsed into a WHERE statement
4459        returning: sql conditional parsed into a RETURNING statement
4460        dialect: the dialect used to parse the input expressions.
4461        **opts: other options to use to parse the input expressions.
4462
4463    Returns:
4464        Delete: the syntax tree for the DELETE statement.
4465    """
4466    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
4467    if where:
4468        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
4469    if returning:
4470        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
4471    return delete_expr
4472
4473
4474def condition(expression, dialect=None, **opts) -> Condition:
4475    """
4476    Initialize a logical condition expression.
4477
4478    Example:
4479        >>> condition("x=1").sql()
4480        'x = 1'
4481
4482        This is helpful for composing larger logical syntax trees:
4483        >>> where = condition("x=1")
4484        >>> where = where.and_("y=1")
4485        >>> Select().from_("tbl").select("*").where(where).sql()
4486        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
4487
4488    Args:
4489        *expression (str | Expression): the SQL code string to parse.
4490            If an Expression instance is passed, this is used as-is.
4491        dialect (str): the dialect used to parse the input expression (in the case that the
4492            input expression is a SQL string).
4493        **opts: other options to use to parse the input expressions (again, in the case
4494            that the input expression is a SQL string).
4495
4496    Returns:
4497        Condition: the expression
4498    """
4499    return maybe_parse(  # type: ignore
4500        expression,
4501        into=Condition,
4502        dialect=dialect,
4503        **opts,
4504    )
4505
4506
4507def and_(*expressions, dialect=None, **opts) -> And:
4508    """
4509    Combine multiple conditions with an AND logical operator.
4510
4511    Example:
4512        >>> and_("x=1", and_("y=1", "z=1")).sql()
4513        'x = 1 AND (y = 1 AND z = 1)'
4514
4515    Args:
4516        *expressions (str | Expression): the SQL code strings to parse.
4517            If an Expression instance is passed, this is used as-is.
4518        dialect (str): the dialect used to parse the input expression.
4519        **opts: other options to use to parse the input expressions.
4520
4521    Returns:
4522        And: the new condition
4523    """
4524    return _combine(expressions, And, dialect, **opts)
4525
4526
4527def or_(*expressions, dialect=None, **opts) -> Or:
4528    """
4529    Combine multiple conditions with an OR logical operator.
4530
4531    Example:
4532        >>> or_("x=1", or_("y=1", "z=1")).sql()
4533        'x = 1 OR (y = 1 OR z = 1)'
4534
4535    Args:
4536        *expressions (str | Expression): the SQL code strings to parse.
4537            If an Expression instance is passed, this is used as-is.
4538        dialect (str): the dialect used to parse the input expression.
4539        **opts: other options to use to parse the input expressions.
4540
4541    Returns:
4542        Or: the new condition
4543    """
4544    return _combine(expressions, Or, dialect, **opts)
4545
4546
4547def not_(expression, dialect=None, **opts) -> Not:
4548    """
4549    Wrap a condition with a NOT operator.
4550
4551    Example:
4552        >>> not_("this_suit='black'").sql()
4553        "NOT this_suit = 'black'"
4554
4555    Args:
4556        expression (str | Expression): the SQL code strings to parse.
4557            If an Expression instance is passed, this is used as-is.
4558        dialect (str): the dialect used to parse the input expression.
4559        **opts: other options to use to parse the input expressions.
4560
4561    Returns:
4562        Not: the new condition
4563    """
4564    this = condition(
4565        expression,
4566        dialect=dialect,
4567        **opts,
4568    )
4569    return Not(this=_wrap_operator(this))
4570
4571
4572def paren(expression) -> Paren:
4573    return Paren(this=expression)
4574
4575
4576SAFE_IDENTIFIER_RE = re.compile(r"^[_a-zA-Z][\w]*$")
4577
4578
4579@t.overload
4580def to_identifier(name: None, quoted: t.Optional[bool] = None) -> None:
4581    ...
4582
4583
4584@t.overload
4585def to_identifier(name: str | Identifier, quoted: t.Optional[bool] = None) -> Identifier:
4586    ...
4587
4588
4589def to_identifier(name, quoted=None):
4590    """Builds an identifier.
4591
4592    Args:
4593        name: The name to turn into an identifier.
4594        quoted: Whether or not force quote the identifier.
4595
4596    Returns:
4597        The identifier ast node.
4598    """
4599
4600    if name is None:
4601        return None
4602
4603    if isinstance(name, Identifier):
4604        identifier = name
4605    elif isinstance(name, str):
4606        identifier = Identifier(
4607            this=name,
4608            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
4609        )
4610    else:
4611        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
4612    return identifier
4613
4614
4615INTERVAL_STRING_RE = re.compile(r"\s*([0-9]+)\s*([a-zA-Z]+)\s*")
4616
4617
4618def to_interval(interval: str | Literal) -> Interval:
4619    """Builds an interval expression from a string like '1 day' or '5 months'."""
4620    if isinstance(interval, Literal):
4621        if not interval.is_string:
4622            raise ValueError("Invalid interval string.")
4623
4624        interval = interval.this
4625
4626    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
4627
4628    if not interval_parts:
4629        raise ValueError("Invalid interval string.")
4630
4631    return Interval(
4632        this=Literal.string(interval_parts.group(1)),
4633        unit=Var(this=interval_parts.group(2)),
4634    )
4635
4636
4637@t.overload
4638def to_table(sql_path: str | Table, **kwargs) -> Table:
4639    ...
4640
4641
4642@t.overload
4643def to_table(sql_path: None, **kwargs) -> None:
4644    ...
4645
4646
4647def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]:
4648    """
4649    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
4650    If a table is passed in then that table is returned.
4651
4652    Args:
4653        sql_path: a `[catalog].[schema].[table]` string.
4654
4655    Returns:
4656        A table expression.
4657    """
4658    if sql_path is None or isinstance(sql_path, Table):
4659        return sql_path
4660    if not isinstance(sql_path, str):
4661        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
4662
4663    catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3))
4664    return Table(this=table_name, db=db, catalog=catalog, **kwargs)
4665
4666
4667def to_column(sql_path: str | Column, **kwargs) -> Column:
4668    """
4669    Create a column from a `[table].[column]` sql path. Schema is optional.
4670
4671    If a column is passed in then that column is returned.
4672
4673    Args:
4674        sql_path: `[table].[column]` string
4675    Returns:
4676        Table: A column expression
4677    """
4678    if sql_path is None or isinstance(sql_path, Column):
4679        return sql_path
4680    if not isinstance(sql_path, str):
4681        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
4682    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore
4683
4684
4685def alias_(
4686    expression: ExpOrStr,
4687    alias: str | Identifier,
4688    table: bool | t.Sequence[str | Identifier] = False,
4689    quoted: t.Optional[bool] = None,
4690    dialect: DialectType = None,
4691    **opts,
4692):
4693    """Create an Alias expression.
4694
4695    Example:
4696        >>> alias_('foo', 'bar').sql()
4697        'foo AS bar'
4698
4699        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
4700        '(SELECT 1, 2) AS bar(a, b)'
4701
4702    Args:
4703        expression: the SQL code strings to parse.
4704            If an Expression instance is passed, this is used as-is.
4705        alias: the alias name to use. If the name has
4706            special characters it is quoted.
4707        table: Whether or not to create a table alias, can also be a list of columns.
4708        quoted: whether or not to quote the alias
4709        dialect: the dialect used to parse the input expression.
4710        **opts: other options to use to parse the input expressions.
4711
4712    Returns:
4713        Alias: the aliased expression
4714    """
4715    exp = maybe_parse(expression, dialect=dialect, **opts)
4716    alias = to_identifier(alias, quoted=quoted)
4717
4718    if table:
4719        table_alias = TableAlias(this=alias)
4720        exp.set("alias", table_alias)
4721
4722        if not isinstance(table, bool):
4723            for column in table:
4724                table_alias.append("columns", to_identifier(column, quoted=quoted))
4725
4726        return exp
4727
4728    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
4729    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
4730    # for the complete Window expression.
4731    #
4732    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
4733
4734    if "alias" in exp.arg_types and not isinstance(exp, Window):
4735        exp = exp.copy()
4736        exp.set("alias", alias)
4737        return exp
4738    return Alias(this=exp, alias=alias)
4739
4740
4741def subquery(expression, alias=None, dialect=None, **opts):
4742    """
4743    Build a subquery expression.
4744
4745    Example:
4746        >>> subquery('select x from tbl', 'bar').select('x').sql()
4747        'SELECT x FROM (SELECT x FROM tbl) AS bar'
4748
4749    Args:
4750        expression (str | Expression): the SQL code strings to parse.
4751            If an Expression instance is passed, this is used as-is.
4752        alias (str | Expression): the alias name to use.
4753        dialect (str): the dialect used to parse the input expression.
4754        **opts: other options to use to parse the input expressions.
4755
4756    Returns:
4757        Select: a new select with the subquery expression included
4758    """
4759
4760    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
4761    return Select().from_(expression, dialect=dialect, **opts)
4762
4763
4764def column(
4765    col: str | Identifier,
4766    table: t.Optional[str | Identifier] = None,
4767    db: t.Optional[str | Identifier] = None,
4768    catalog: t.Optional[str | Identifier] = None,
4769    quoted: t.Optional[bool] = None,
4770) -> Column:
4771    """
4772    Build a Column.
4773
4774    Args:
4775        col: column name
4776        table: table name
4777        db: db name
4778        catalog: catalog name
4779        quoted: whether or not to force quote each part
4780    Returns:
4781        Column: column instance
4782    """
4783    return Column(
4784        this=to_identifier(col, quoted=quoted),
4785        table=to_identifier(table, quoted=quoted),
4786        db=to_identifier(db, quoted=quoted),
4787        catalog=to_identifier(catalog, quoted=quoted),
4788    )
4789
4790
4791def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
4792    """Cast an expression to a data type.
4793
4794    Example:
4795        >>> cast('x + 1', 'int').sql()
4796        'CAST(x + 1 AS INT)'
4797
4798    Args:
4799        expression: The expression to cast.
4800        to: The datatype to cast to.
4801
4802    Returns:
4803        A cast node.
4804    """
4805    expression = maybe_parse(expression, **opts)
4806    return Cast(this=expression, to=DataType.build(to, **opts))
4807
4808
4809def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table:
4810    """Build a Table.
4811
4812    Args:
4813        table (str | Expression): column name
4814        db (str | Expression): db name
4815        catalog (str | Expression): catalog name
4816
4817    Returns:
4818        Table: table instance
4819    """
4820    return Table(
4821        this=to_identifier(table, quoted=quoted),
4822        db=to_identifier(db, quoted=quoted),
4823        catalog=to_identifier(catalog, quoted=quoted),
4824        alias=TableAlias(this=to_identifier(alias)) if alias else None,
4825    )
4826
4827
4828def values(
4829    values: t.Iterable[t.Tuple[t.Any, ...]],
4830    alias: t.Optional[str] = None,
4831    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
4832) -> Values:
4833    """Build VALUES statement.
4834
4835    Example:
4836        >>> values([(1, '2')]).sql()
4837        "VALUES (1, '2')"
4838
4839    Args:
4840        values: values statements that will be converted to SQL
4841        alias: optional alias
4842        columns: Optional list of ordered column names or ordered dictionary of column names to types.
4843         If either are provided then an alias is also required.
4844         If a dictionary is provided then the first column of the values will be casted to the expected type
4845         in order to help with type inference.
4846
4847    Returns:
4848        Values: the Values expression object
4849    """
4850    if columns and not alias:
4851        raise ValueError("Alias is required when providing columns")
4852    table_alias = (
4853        TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
4854        if columns
4855        else TableAlias(this=to_identifier(alias) if alias else None)
4856    )
4857    expressions = [convert(tup) for tup in values]
4858    if columns and isinstance(columns, dict):
4859        types = list(columns.values())
4860        expressions[0].set(
4861            "expressions",
4862            [cast(x, types[i]) for i, x in enumerate(expressions[0].expressions)],
4863        )
4864    return Values(
4865        expressions=expressions,
4866        alias=table_alias,
4867    )
4868
4869
4870def var(name: t.Optional[ExpOrStr]) -> Var:
4871    """Build a SQL variable.
4872
4873    Example:
4874        >>> repr(var('x'))
4875        '(VAR this: x)'
4876
4877        >>> repr(var(column('x', table='y')))
4878        '(VAR this: x)'
4879
4880    Args:
4881        name: The name of the var or an expression who's name will become the var.
4882
4883    Returns:
4884        The new variable node.
4885    """
4886    if not name:
4887        raise ValueError("Cannot convert empty name into var.")
4888
4889    if isinstance(name, Expression):
4890        name = name.name
4891    return Var(this=name)
4892
4893
4894def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
4895    """Build ALTER TABLE... RENAME... expression
4896
4897    Args:
4898        old_name: The old name of the table
4899        new_name: The new name of the table
4900
4901    Returns:
4902        Alter table expression
4903    """
4904    old_table = to_table(old_name)
4905    new_table = to_table(new_name)
4906    return AlterTable(
4907        this=old_table,
4908        actions=[
4909            RenameTable(this=new_table),
4910        ],
4911    )
4912
4913
4914def convert(value) -> Expression:
4915    """Convert a python value into an expression object.
4916
4917    Raises an error if a conversion is not possible.
4918
4919    Args:
4920        value (Any): a python object
4921
4922    Returns:
4923        Expression: the equivalent expression object
4924    """
4925    if isinstance(value, Expression):
4926        return value
4927    if value is None:
4928        return NULL
4929    if isinstance(value, bool):
4930        return Boolean(this=value)
4931    if isinstance(value, str):
4932        return Literal.string(value)
4933    if isinstance(value, float) and math.isnan(value):
4934        return NULL
4935    if isinstance(value, numbers.Number):
4936        return Literal.number(value)
4937    if isinstance(value, tuple):
4938        return Tuple(expressions=[convert(v) for v in value])
4939    if isinstance(value, list):
4940        return Array(expressions=[convert(v) for v in value])
4941    if isinstance(value, dict):
4942        return Map(
4943            keys=[convert(k) for k in value],
4944            values=[convert(v) for v in value.values()],
4945        )
4946    if isinstance(value, datetime.datetime):
4947        datetime_literal = Literal.string(
4948            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
4949        )
4950        return TimeStrToTime(this=datetime_literal)
4951    if isinstance(value, datetime.date):
4952        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
4953        return DateStrToDate(this=date_literal)
4954    raise ValueError(f"Cannot convert {value}")
4955
4956
4957def replace_children(expression, fun, *args, **kwargs):
4958    """
4959    Replace children of an expression with the result of a lambda fun(child) -> exp.
4960    """
4961    for k, v in expression.args.items():
4962        is_list_arg = type(v) is list
4963
4964        child_nodes = v if is_list_arg else [v]
4965        new_child_nodes = []
4966
4967        for cn in child_nodes:
4968            if isinstance(cn, Expression):
4969                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
4970                    new_child_nodes.append(child_node)
4971                    child_node.parent = expression
4972                    child_node.arg_key = k
4973            else:
4974                new_child_nodes.append(cn)
4975
4976        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)
4977
4978
4979def column_table_names(expression):
4980    """
4981    Return all table names referenced through columns in an expression.
4982
4983    Example:
4984        >>> import sqlglot
4985        >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
4986        ['c', 'a']
4987
4988    Args:
4989        expression (sqlglot.Expression): expression to find table names
4990
4991    Returns:
4992        list: A list of unique names
4993    """
4994    return list(dict.fromkeys(column.table for column in expression.find_all(Column)))
4995
4996
4997def table_name(table) -> str:
4998    """Get the full name of a table as a string.
4999
5000    Args:
5001        table (exp.Table | str): table expression node or string.
5002
5003    Examples:
5004        >>> from sqlglot import exp, parse_one
5005        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5006        'a.b.c'
5007
5008    Returns:
5009        The table name.
5010    """
5011
5012    table = maybe_parse(table, into=Table)
5013
5014    if not table:
5015        raise ValueError(f"Cannot parse {table}")
5016
5017    return ".".join(
5018        part
5019        for part in (
5020            table.text("catalog"),
5021            table.text("db"),
5022            table.name,
5023        )
5024        if part
5025    )
5026
5027
5028def replace_tables(expression, mapping):
5029    """Replace all tables in expression according to the mapping.
5030
5031    Args:
5032        expression (sqlglot.Expression): expression node to be transformed and replaced.
5033        mapping (Dict[str, str]): mapping of table names.
5034
5035    Examples:
5036        >>> from sqlglot import exp, parse_one
5037        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5038        'SELECT * FROM c'
5039
5040    Returns:
5041        The mapped expression.
5042    """
5043
5044    def _replace_tables(node):
5045        if isinstance(node, Table):
5046            new_name = mapping.get(table_name(node))
5047            if new_name:
5048                return to_table(
5049                    new_name,
5050                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5051                )
5052        return node
5053
5054    return expression.transform(_replace_tables)
5055
5056
5057def replace_placeholders(expression, *args, **kwargs):
5058    """Replace placeholders in an expression.
5059
5060    Args:
5061        expression (sqlglot.Expression): expression node to be transformed and replaced.
5062        args: positional names that will substitute unnamed placeholders in the given order.
5063        kwargs: keyword arguments that will substitute named placeholders.
5064
5065    Examples:
5066        >>> from sqlglot import exp, parse_one
5067        >>> replace_placeholders(
5068        ...     parse_one("select * from :tbl where ? = ?"),
5069        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5070        ... ).sql()
5071        "SELECT * FROM foo WHERE str_col = 'b'"
5072
5073    Returns:
5074        The mapped expression.
5075    """
5076
5077    def _replace_placeholders(node, args, **kwargs):
5078        if isinstance(node, Placeholder):
5079            if node.name:
5080                new_name = kwargs.get(node.name)
5081                if new_name:
5082                    return convert(new_name)
5083            else:
5084                try:
5085                    return convert(next(args))
5086                except StopIteration:
5087                    pass
5088        return node
5089
5090    return expression.transform(_replace_placeholders, iter(args), **kwargs)
5091
5092
5093def expand(
5094    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5095) -> Expression:
5096    """Transforms an expression by expanding all referenced sources into subqueries.
5097
5098    Examples:
5099        >>> from sqlglot import parse_one
5100        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5101        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5102
5103        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5104        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5105
5106    Args:
5107        expression: The expression to expand.
5108        sources: A dictionary of name to Subqueryables.
5109        copy: Whether or not to copy the expression during transformation. Defaults to True.
5110
5111    Returns:
5112        The transformed expression.
5113    """
5114
5115    def _expand(node: Expression):
5116        if isinstance(node, Table):
5117            name = table_name(node)
5118            source = sources.get(name)
5119            if source:
5120                subquery = source.subquery(node.alias or name)
5121                subquery.comments = [f"source: {name}"]
5122                return subquery.transform(_expand, copy=False)
5123        return node
5124
5125    return expression.transform(_expand, copy=copy)
5126
5127
5128def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5129    """
5130    Returns a Func expression.
5131
5132    Examples:
5133        >>> func("abs", 5).sql()
5134        'ABS(5)'
5135
5136        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5137        'CAST(5 AS DOUBLE)'
5138
5139    Args:
5140        name: the name of the function to build.
5141        args: the args used to instantiate the function of interest.
5142        dialect: the source dialect.
5143        kwargs: the kwargs used to instantiate the function of interest.
5144
5145    Note:
5146        The arguments `args` and `kwargs` are mutually exclusive.
5147
5148    Returns:
5149        An instance of the function of interest, or an anonymous function, if `name` doesn't
5150        correspond to an existing `sqlglot.expressions.Func` class.
5151    """
5152    if args and kwargs:
5153        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5154
5155    from sqlglot.dialects.dialect import Dialect
5156
5157    converted = [convert(arg) for arg in args]
5158    kwargs = {key: convert(value) for key, value in kwargs.items()}
5159
5160    parser = Dialect.get_or_raise(dialect)().parser()
5161    from_args_list = parser.FUNCTIONS.get(name.upper())
5162
5163    if from_args_list:
5164        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5165    else:
5166        kwargs = kwargs or {"expressions": converted}
5167        function = Anonymous(this=name, **kwargs)
5168
5169    for error_message in function.error_messages(converted):
5170        raise ValueError(error_message)
5171
5172    return function
5173
5174
5175def true():
5176    """
5177    Returns a true Boolean expression.
5178    """
5179    return Boolean(this=True)
5180
5181
5182def false():
5183    """
5184    Returns a false Boolean expression.
5185    """
5186    return Boolean(this=False)
5187
5188
5189def null():
5190    """
5191    Returns a Null expression.
5192    """
5193    return Null()
5194
5195
5196# TODO: deprecate this
5197TRUE = Boolean(this=True)
5198FALSE = Boolean(this=False)
5199NULL = Null()
class Expression:
 57class Expression(metaclass=_Expression):
 58    """
 59    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
 60    context, such as its child expressions, their names (arg keys), and whether a given child expression
 61    is optional or not.
 62
 63    Attributes:
 64        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
 65            and representing expressions as strings.
 66        arg_types: determines what arguments (child nodes) are supported by an expression. It
 67            maps arg keys to booleans that indicate whether the corresponding args are optional.
 68
 69    Example:
 70        >>> class Foo(Expression):
 71        ...     arg_types = {"this": True, "expression": False}
 72
 73        The above definition informs us that Foo is an Expression that requires an argument called
 74        "this" and may also optionally receive an argument called "expression".
 75
 76    Args:
 77        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
 78        parent: a reference to the parent expression (or None, in case of root expressions).
 79        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
 80            uses to refer to it.
 81        comments: a list of comments that are associated with a given expression. This is used in
 82            order to preserve comments when transpiling SQL code.
 83        _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
 84            optimizer, in order to enable some transformations that require type information.
 85    """
 86
 87    key = "expression"
 88    arg_types = {"this": True}
 89    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash")
 90
 91    def __init__(self, **args: t.Any):
 92        self.args: t.Dict[str, t.Any] = args
 93        self.parent: t.Optional[Expression] = None
 94        self.arg_key: t.Optional[str] = None
 95        self.comments: t.Optional[t.List[str]] = None
 96        self._type: t.Optional[DataType] = None
 97        self._meta: t.Optional[t.Dict[str, t.Any]] = None
 98        self._hash: t.Optional[int] = None
 99
100        for arg_key, value in self.args.items():
101            self._set_parent(arg_key, value)
102
103    def __eq__(self, other) -> bool:
104        return type(self) is type(other) and hash(self) == hash(other)
105
106    @property
107    def hashable_args(self) -> t.Any:
108        args = (self.args.get(k) for k in self.arg_types)
109
110        return tuple(
111            (tuple(_norm_arg(a) for a in arg) if arg else None)
112            if type(arg) is list
113            else (_norm_arg(arg) if arg is not None and arg is not False else None)
114            for arg in args
115        )
116
117    def __hash__(self) -> int:
118        if self._hash is not None:
119            return self._hash
120
121        return hash((self.__class__, self.hashable_args))
122
123    @property
124    def this(self):
125        """
126        Retrieves the argument with key "this".
127        """
128        return self.args.get("this")
129
130    @property
131    def expression(self):
132        """
133        Retrieves the argument with key "expression".
134        """
135        return self.args.get("expression")
136
137    @property
138    def expressions(self):
139        """
140        Retrieves the argument with key "expressions".
141        """
142        return self.args.get("expressions") or []
143
144    def text(self, key) -> str:
145        """
146        Returns a textual representation of the argument corresponding to "key". This can only be used
147        for args that are strings or leaf Expression instances, such as identifiers and literals.
148        """
149        field = self.args.get(key)
150        if isinstance(field, str):
151            return field
152        if isinstance(field, (Identifier, Literal, Var)):
153            return field.this
154        if isinstance(field, (Star, Null)):
155            return field.name
156        return ""
157
158    @property
159    def is_string(self) -> bool:
160        """
161        Checks whether a Literal expression is a string.
162        """
163        return isinstance(self, Literal) and self.args["is_string"]
164
165    @property
166    def is_number(self) -> bool:
167        """
168        Checks whether a Literal expression is a number.
169        """
170        return isinstance(self, Literal) and not self.args["is_string"]
171
172    @property
173    def is_int(self) -> bool:
174        """
175        Checks whether a Literal expression is an integer.
176        """
177        if self.is_number:
178            try:
179                int(self.name)
180                return True
181            except ValueError:
182                pass
183        return False
184
185    @property
186    def is_star(self) -> bool:
187        """Checks whether an expression is a star."""
188        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
189
190    @property
191    def alias(self) -> str:
192        """
193        Returns the alias of the expression, or an empty string if it's not aliased.
194        """
195        if isinstance(self.args.get("alias"), TableAlias):
196            return self.args["alias"].name
197        return self.text("alias")
198
199    @property
200    def name(self) -> str:
201        return self.text("this")
202
203    @property
204    def alias_or_name(self):
205        return self.alias or self.name
206
207    @property
208    def output_name(self):
209        """
210        Name of the output column if this expression is a selection.
211
212        If the Expression has no output name, an empty string is returned.
213
214        Example:
215            >>> from sqlglot import parse_one
216            >>> parse_one("SELECT a").expressions[0].output_name
217            'a'
218            >>> parse_one("SELECT b AS c").expressions[0].output_name
219            'c'
220            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
221            ''
222        """
223        return ""
224
225    @property
226    def type(self) -> t.Optional[DataType]:
227        return self._type
228
229    @type.setter
230    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
231        if dtype and not isinstance(dtype, DataType):
232            dtype = DataType.build(dtype)
233        self._type = dtype  # type: ignore
234
235    @property
236    def meta(self) -> t.Dict[str, t.Any]:
237        if self._meta is None:
238            self._meta = {}
239        return self._meta
240
241    def __deepcopy__(self, memo):
242        copy = self.__class__(**deepcopy(self.args))
243        if self.comments is not None:
244            copy.comments = deepcopy(self.comments)
245
246        if self._type is not None:
247            copy._type = self._type.copy()
248
249        if self._meta is not None:
250            copy._meta = deepcopy(self._meta)
251
252        return copy
253
254    def copy(self):
255        """
256        Returns a deep copy of the expression.
257        """
258        new = deepcopy(self)
259        new.parent = self.parent
260        return new
261
262    def append(self, arg_key, value):
263        """
264        Appends value to arg_key if it's a list or sets it as a new list.
265
266        Args:
267            arg_key (str): name of the list expression arg
268            value (Any): value to append to the list
269        """
270        if not isinstance(self.args.get(arg_key), list):
271            self.args[arg_key] = []
272        self.args[arg_key].append(value)
273        self._set_parent(arg_key, value)
274
275    def set(self, arg_key, value):
276        """
277        Sets `arg_key` to `value`.
278
279        Args:
280            arg_key (str): name of the expression arg.
281            value: value to set the arg to.
282        """
283        self.args[arg_key] = value
284        self._set_parent(arg_key, value)
285
286    def _set_parent(self, arg_key, value):
287        if hasattr(value, "parent"):
288            value.parent = self
289            value.arg_key = arg_key
290        elif type(value) is list:
291            for v in value:
292                if hasattr(v, "parent"):
293                    v.parent = self
294                    v.arg_key = arg_key
295
296    @property
297    def depth(self):
298        """
299        Returns the depth of this tree.
300        """
301        if self.parent:
302            return self.parent.depth + 1
303        return 0
304
305    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
306        """Yields the key and expression for all arguments, exploding list args."""
307        for k, vs in self.args.items():
308            if type(vs) is list:
309                for v in vs:
310                    if hasattr(v, "parent"):
311                        yield k, v
312            else:
313                if hasattr(vs, "parent"):
314                    yield k, vs
315
316    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
317        """
318        Returns the first node in this tree which matches at least one of
319        the specified types.
320
321        Args:
322            expression_types: the expression type(s) to match.
323
324        Returns:
325            The node which matches the criteria or None if no such node was found.
326        """
327        return next(self.find_all(*expression_types, bfs=bfs), None)
328
329    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
330        """
331        Returns a generator object which visits all nodes in this tree and only
332        yields those that match at least one of the specified expression types.
333
334        Args:
335            expression_types: the expression type(s) to match.
336
337        Returns:
338            The generator object.
339        """
340        for expression, *_ in self.walk(bfs=bfs):
341            if isinstance(expression, expression_types):
342                yield expression
343
344    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
345        """
346        Returns a nearest parent matching expression_types.
347
348        Args:
349            expression_types: the expression type(s) to match.
350
351        Returns:
352            The parent node.
353        """
354        ancestor = self.parent
355        while ancestor and not isinstance(ancestor, expression_types):
356            ancestor = ancestor.parent
357        return t.cast(E, ancestor)
358
359    @property
360    def parent_select(self):
361        """
362        Returns the parent select statement.
363        """
364        return self.find_ancestor(Select)
365
366    @property
367    def same_parent(self):
368        """Returns if the parent is the same class as itself."""
369        return type(self.parent) is self.__class__
370
371    def root(self) -> Expression:
372        """
373        Returns the root expression of this tree.
374        """
375        expression = self
376        while expression.parent:
377            expression = expression.parent
378        return expression
379
380    def walk(self, bfs=True, prune=None):
381        """
382        Returns a generator object which visits all nodes in this tree.
383
384        Args:
385            bfs (bool): if set to True the BFS traversal order will be applied,
386                otherwise the DFS traversal will be used instead.
387            prune ((node, parent, arg_key) -> bool): callable that returns True if
388                the generator should stop traversing this branch of the tree.
389
390        Returns:
391            the generator object.
392        """
393        if bfs:
394            yield from self.bfs(prune=prune)
395        else:
396            yield from self.dfs(prune=prune)
397
398    def dfs(self, parent=None, key=None, prune=None):
399        """
400        Returns a generator object which visits all nodes in this tree in
401        the DFS (Depth-first) order.
402
403        Returns:
404            The generator object.
405        """
406        parent = parent or self.parent
407        yield self, parent, key
408        if prune and prune(self, parent, key):
409            return
410
411        for k, v in self.iter_expressions():
412            yield from v.dfs(self, k, prune)
413
414    def bfs(self, prune=None):
415        """
416        Returns a generator object which visits all nodes in this tree in
417        the BFS (Breadth-first) order.
418
419        Returns:
420            The generator object.
421        """
422        queue = deque([(self, self.parent, None)])
423
424        while queue:
425            item, parent, key = queue.popleft()
426
427            yield item, parent, key
428            if prune and prune(item, parent, key):
429                continue
430
431            for k, v in item.iter_expressions():
432                queue.append((v, item, k))
433
434    def unnest(self):
435        """
436        Returns the first non parenthesis child or self.
437        """
438        expression = self
439        while type(expression) is Paren:
440            expression = expression.this
441        return expression
442
443    def unalias(self):
444        """
445        Returns the inner expression if this is an Alias.
446        """
447        if isinstance(self, Alias):
448            return self.this
449        return self
450
451    def unnest_operands(self):
452        """
453        Returns unnested operands as a tuple.
454        """
455        return tuple(arg.unnest() for _, arg in self.iter_expressions())
456
457    def flatten(self, unnest=True):
458        """
459        Returns a generator which yields child nodes who's parents are the same class.
460
461        A AND B AND C -> [A, B, C]
462        """
463        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
464            if not type(node) is self.__class__:
465                yield node.unnest() if unnest else node
466
467    def __str__(self):
468        return self.sql()
469
470    def __repr__(self):
471        return self._to_s()
472
473    def sql(self, dialect: DialectType = None, **opts) -> str:
474        """
475        Returns SQL string representation of this tree.
476
477        Args:
478            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
479            opts: other `sqlglot.generator.Generator` options.
480
481        Returns:
482            The SQL string.
483        """
484        from sqlglot.dialects import Dialect
485
486        return Dialect.get_or_raise(dialect)().generate(self, **opts)
487
488    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
489        indent = "" if not level else "\n"
490        indent += "".join(["  "] * level)
491        left = f"({self.key.upper()} "
492
493        args: t.Dict[str, t.Any] = {
494            k: ", ".join(
495                v._to_s(hide_missing=hide_missing, level=level + 1)
496                if hasattr(v, "_to_s")
497                else str(v)
498                for v in ensure_list(vs)
499                if v is not None
500            )
501            for k, vs in self.args.items()
502        }
503        args["comments"] = self.comments
504        args["type"] = self.type
505        args = {k: v for k, v in args.items() if v or not hide_missing}
506
507        right = ", ".join(f"{k}: {v}" for k, v in args.items())
508        right += ")"
509
510        return indent + left + right
511
512    def transform(self, fun, *args, copy=True, **kwargs):
513        """
514        Recursively visits all tree nodes (excluding already transformed ones)
515        and applies the given transformation function to each node.
516
517        Args:
518            fun (function): a function which takes a node as an argument and returns a
519                new transformed node or the same node without modifications. If the function
520                returns None, then the corresponding node will be removed from the syntax tree.
521            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
522                modified in place.
523
524        Returns:
525            The transformed tree.
526        """
527        node = self.copy() if copy else self
528        new_node = fun(node, *args, **kwargs)
529
530        if new_node is None or not isinstance(new_node, Expression):
531            return new_node
532        if new_node is not node:
533            new_node.parent = node.parent
534            return new_node
535
536        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
537        return new_node
538
539    def replace(self, expression):
540        """
541        Swap out this expression with a new expression.
542
543        For example::
544
545            >>> tree = Select().select("x").from_("tbl")
546            >>> tree.find(Column).replace(Column(this="y"))
547            (COLUMN this: y)
548            >>> tree.sql()
549            'SELECT y FROM tbl'
550
551        Args:
552            expression (Expression|None): new node
553
554        Returns:
555            The new expression or expressions.
556        """
557        if not self.parent:
558            return expression
559
560        parent = self.parent
561        self.parent = None
562
563        replace_children(parent, lambda child: expression if child is self else child)
564        return expression
565
566    def pop(self):
567        """
568        Remove this expression from its AST.
569
570        Returns:
571            The popped expression.
572        """
573        self.replace(None)
574        return self
575
576    def assert_is(self, type_):
577        """
578        Assert that this `Expression` is an instance of `type_`.
579
580        If it is NOT an instance of `type_`, this raises an assertion error.
581        Otherwise, this returns this expression.
582
583        Examples:
584            This is useful for type security in chained expressions:
585
586            >>> import sqlglot
587            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
588            'SELECT x, z FROM y'
589        """
590        assert isinstance(self, type_)
591        return self
592
593    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
594        """
595        Checks if this expression is valid (e.g. all mandatory args are set).
596
597        Args:
598            args: a sequence of values that were used to instantiate a Func expression. This is used
599                to check that the provided arguments don't exceed the function argument limit.
600
601        Returns:
602            A list of error messages for all possible errors that were found.
603        """
604        errors: t.List[str] = []
605
606        for k in self.args:
607            if k not in self.arg_types:
608                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
609        for k, mandatory in self.arg_types.items():
610            v = self.args.get(k)
611            if mandatory and (v is None or (isinstance(v, list) and not v)):
612                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
613
614        if (
615            args
616            and isinstance(self, Func)
617            and len(args) > len(self.arg_types)
618            and not self.is_var_len_args
619        ):
620            errors.append(
621                f"The number of provided arguments ({len(args)}) is greater than "
622                f"the maximum number of supported arguments ({len(self.arg_types)})"
623            )
624
625        return errors
626
627    def dump(self):
628        """
629        Dump this Expression to a JSON-serializable dict.
630        """
631        from sqlglot.serde import dump
632
633        return dump(self)
634
635    @classmethod
636    def load(cls, obj):
637        """
638        Load a dict (as returned by `Expression.dump`) into an Expression instance.
639        """
640        from sqlglot.serde import load
641
642        return load(obj)

The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary context, such as its child expressions, their names (arg keys), and whether a given child expression is optional or not.

Attributes:
  • key: a unique key for each class in the Expression hierarchy. This is useful for hashing and representing expressions as strings.
  • arg_types: determines what arguments (child nodes) are supported by an expression. It maps arg keys to booleans that indicate whether the corresponding args are optional.
Example:
>>> class Foo(Expression):
...     arg_types = {"this": True, "expression": False}

The above definition informs us that Foo is an Expression that requires an argument called "this" and may also optionally receive an argument called "expression".

Arguments:
  • args: a mapping used for retrieving the arguments of an expression, given their arg keys.
  • parent: a reference to the parent expression (or None, in case of root expressions).
  • arg_key: the arg key an expression is associated with, i.e. the name its parent expression uses to refer to it.
  • comments: a list of comments that are associated with a given expression. This is used in order to preserve comments when transpiling SQL code.
  • _type: the sqlglot.expressions.DataType type of an expression. This is inferred by the optimizer, in order to enable some transformations that require type information.
Expression(**args: Any)
 91    def __init__(self, **args: t.Any):
 92        self.args: t.Dict[str, t.Any] = args
 93        self.parent: t.Optional[Expression] = None
 94        self.arg_key: t.Optional[str] = None
 95        self.comments: t.Optional[t.List[str]] = None
 96        self._type: t.Optional[DataType] = None
 97        self._meta: t.Optional[t.Dict[str, t.Any]] = None
 98        self._hash: t.Optional[int] = None
 99
100        for arg_key, value in self.args.items():
101            self._set_parent(arg_key, value)
this

Retrieves the argument with key "this".

expression

Retrieves the argument with key "expression".

expressions

Retrieves the argument with key "expressions".

def text(self, key) -> str:
144    def text(self, key) -> str:
145        """
146        Returns a textual representation of the argument corresponding to "key". This can only be used
147        for args that are strings or leaf Expression instances, such as identifiers and literals.
148        """
149        field = self.args.get(key)
150        if isinstance(field, str):
151            return field
152        if isinstance(field, (Identifier, Literal, Var)):
153            return field.this
154        if isinstance(field, (Star, Null)):
155            return field.name
156        return ""

Returns a textual representation of the argument corresponding to "key". This can only be used for args that are strings or leaf Expression instances, such as identifiers and literals.

is_string: bool

Checks whether a Literal expression is a string.

is_number: bool

Checks whether a Literal expression is a number.

is_int: bool

Checks whether a Literal expression is an integer.

is_star: bool

Checks whether an expression is a star.

alias: str

Returns the alias of the expression, or an empty string if it's not aliased.

output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def copy(self):
254    def copy(self):
255        """
256        Returns a deep copy of the expression.
257        """
258        new = deepcopy(self)
259        new.parent = self.parent
260        return new

Returns a deep copy of the expression.

def append(self, arg_key, value):
262    def append(self, arg_key, value):
263        """
264        Appends value to arg_key if it's a list or sets it as a new list.
265
266        Args:
267            arg_key (str): name of the list expression arg
268            value (Any): value to append to the list
269        """
270        if not isinstance(self.args.get(arg_key), list):
271            self.args[arg_key] = []
272        self.args[arg_key].append(value)
273        self._set_parent(arg_key, value)

Appends value to arg_key if it's a list or sets it as a new list.

Arguments:
  • arg_key (str): name of the list expression arg
  • value (Any): value to append to the list
def set(self, arg_key, value):
275    def set(self, arg_key, value):
276        """
277        Sets `arg_key` to `value`.
278
279        Args:
280            arg_key (str): name of the expression arg.
281            value: value to set the arg to.
282        """
283        self.args[arg_key] = value
284        self._set_parent(arg_key, value)

Sets arg_key to value.

Arguments:
  • arg_key (str): name of the expression arg.
  • value: value to set the arg to.
depth

Returns the depth of this tree.

def iter_expressions(self) -> Iterator[Tuple[str, sqlglot.expressions.Expression]]:
305    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
306        """Yields the key and expression for all arguments, exploding list args."""
307        for k, vs in self.args.items():
308            if type(vs) is list:
309                for v in vs:
310                    if hasattr(v, "parent"):
311                        yield k, v
312            else:
313                if hasattr(vs, "parent"):
314                    yield k, vs

Yields the key and expression for all arguments, exploding list args.

def find(self, *expression_types: Type[~E], bfs=True) -> Optional[~E]:
316    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
317        """
318        Returns the first node in this tree which matches at least one of
319        the specified types.
320
321        Args:
322            expression_types: the expression type(s) to match.
323
324        Returns:
325            The node which matches the criteria or None if no such node was found.
326        """
327        return next(self.find_all(*expression_types, bfs=bfs), None)

Returns the first node in this tree which matches at least one of the specified types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The node which matches the criteria or None if no such node was found.

def find_all(self, *expression_types: Type[~E], bfs=True) -> Iterator[~E]:
329    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
330        """
331        Returns a generator object which visits all nodes in this tree and only
332        yields those that match at least one of the specified expression types.
333
334        Args:
335            expression_types: the expression type(s) to match.
336
337        Returns:
338            The generator object.
339        """
340        for expression, *_ in self.walk(bfs=bfs):
341            if isinstance(expression, expression_types):
342                yield expression

Returns a generator object which visits all nodes in this tree and only yields those that match at least one of the specified expression types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The generator object.

def find_ancestor(self, *expression_types: Type[~E]) -> Optional[~E]:
344    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
345        """
346        Returns a nearest parent matching expression_types.
347
348        Args:
349            expression_types: the expression type(s) to match.
350
351        Returns:
352            The parent node.
353        """
354        ancestor = self.parent
355        while ancestor and not isinstance(ancestor, expression_types):
356            ancestor = ancestor.parent
357        return t.cast(E, ancestor)

Returns a nearest parent matching expression_types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The parent node.

parent_select

Returns the parent select statement.

same_parent

Returns if the parent is the same class as itself.

def root(self) -> sqlglot.expressions.Expression:
371    def root(self) -> Expression:
372        """
373        Returns the root expression of this tree.
374        """
375        expression = self
376        while expression.parent:
377            expression = expression.parent
378        return expression

Returns the root expression of this tree.

def walk(self, bfs=True, prune=None):
380    def walk(self, bfs=True, prune=None):
381        """
382        Returns a generator object which visits all nodes in this tree.
383
384        Args:
385            bfs (bool): if set to True the BFS traversal order will be applied,
386                otherwise the DFS traversal will be used instead.
387            prune ((node, parent, arg_key) -> bool): callable that returns True if
388                the generator should stop traversing this branch of the tree.
389
390        Returns:
391            the generator object.
392        """
393        if bfs:
394            yield from self.bfs(prune=prune)
395        else:
396            yield from self.dfs(prune=prune)

Returns a generator object which visits all nodes in this tree.

Arguments:
  • bfs (bool): if set to True the BFS traversal order will be applied, otherwise the DFS traversal will be used instead.
  • prune ((node, parent, arg_key) -> bool): callable that returns True if the generator should stop traversing this branch of the tree.
Returns:

the generator object.

def dfs(self, parent=None, key=None, prune=None):
398    def dfs(self, parent=None, key=None, prune=None):
399        """
400        Returns a generator object which visits all nodes in this tree in
401        the DFS (Depth-first) order.
402
403        Returns:
404            The generator object.
405        """
406        parent = parent or self.parent
407        yield self, parent, key
408        if prune and prune(self, parent, key):
409            return
410
411        for k, v in self.iter_expressions():
412            yield from v.dfs(self, k, prune)

Returns a generator object which visits all nodes in this tree in the DFS (Depth-first) order.

Returns:

The generator object.

def bfs(self, prune=None):
414    def bfs(self, prune=None):
415        """
416        Returns a generator object which visits all nodes in this tree in
417        the BFS (Breadth-first) order.
418
419        Returns:
420            The generator object.
421        """
422        queue = deque([(self, self.parent, None)])
423
424        while queue:
425            item, parent, key = queue.popleft()
426
427            yield item, parent, key
428            if prune and prune(item, parent, key):
429                continue
430
431            for k, v in item.iter_expressions():
432                queue.append((v, item, k))

Returns a generator object which visits all nodes in this tree in the BFS (Breadth-first) order.

Returns:

The generator object.

def unnest(self):
434    def unnest(self):
435        """
436        Returns the first non parenthesis child or self.
437        """
438        expression = self
439        while type(expression) is Paren:
440            expression = expression.this
441        return expression

Returns the first non parenthesis child or self.

def unalias(self):
443    def unalias(self):
444        """
445        Returns the inner expression if this is an Alias.
446        """
447        if isinstance(self, Alias):
448            return self.this
449        return self

Returns the inner expression if this is an Alias.

def unnest_operands(self):
451    def unnest_operands(self):
452        """
453        Returns unnested operands as a tuple.
454        """
455        return tuple(arg.unnest() for _, arg in self.iter_expressions())

Returns unnested operands as a tuple.

def flatten(self, unnest=True):
457    def flatten(self, unnest=True):
458        """
459        Returns a generator which yields child nodes who's parents are the same class.
460
461        A AND B AND C -> [A, B, C]
462        """
463        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
464            if not type(node) is self.__class__:
465                yield node.unnest() if unnest else node

Returns a generator which yields child nodes who's parents are the same class.

A AND B AND C -> [A, B, C]

def sql( self, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> str:
473    def sql(self, dialect: DialectType = None, **opts) -> str:
474        """
475        Returns SQL string representation of this tree.
476
477        Args:
478            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
479            opts: other `sqlglot.generator.Generator` options.
480
481        Returns:
482            The SQL string.
483        """
484        from sqlglot.dialects import Dialect
485
486        return Dialect.get_or_raise(dialect)().generate(self, **opts)

Returns SQL string representation of this tree.

Arguments:
  • dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
  • opts: other sqlglot.generator.Generator options.
Returns:

The SQL string.

def transform(self, fun, *args, copy=True, **kwargs):
512    def transform(self, fun, *args, copy=True, **kwargs):
513        """
514        Recursively visits all tree nodes (excluding already transformed ones)
515        and applies the given transformation function to each node.
516
517        Args:
518            fun (function): a function which takes a node as an argument and returns a
519                new transformed node or the same node without modifications. If the function
520                returns None, then the corresponding node will be removed from the syntax tree.
521            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
522                modified in place.
523
524        Returns:
525            The transformed tree.
526        """
527        node = self.copy() if copy else self
528        new_node = fun(node, *args, **kwargs)
529
530        if new_node is None or not isinstance(new_node, Expression):
531            return new_node
532        if new_node is not node:
533            new_node.parent = node.parent
534            return new_node
535
536        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
537        return new_node

Recursively visits all tree nodes (excluding already transformed ones) and applies the given transformation function to each node.

Arguments:
  • fun (function): a function which takes a node as an argument and returns a new transformed node or the same node without modifications. If the function returns None, then the corresponding node will be removed from the syntax tree.
  • copy (bool): if set to True a new tree instance is constructed, otherwise the tree is modified in place.
Returns:

The transformed tree.

def replace(self, expression):
539    def replace(self, expression):
540        """
541        Swap out this expression with a new expression.
542
543        For example::
544
545            >>> tree = Select().select("x").from_("tbl")
546            >>> tree.find(Column).replace(Column(this="y"))
547            (COLUMN this: y)
548            >>> tree.sql()
549            'SELECT y FROM tbl'
550
551        Args:
552            expression (Expression|None): new node
553
554        Returns:
555            The new expression or expressions.
556        """
557        if not self.parent:
558            return expression
559
560        parent = self.parent
561        self.parent = None
562
563        replace_children(parent, lambda child: expression if child is self else child)
564        return expression

Swap out this expression with a new expression.

For example::

>>> tree = Select().select("x").from_("tbl")
>>> tree.find(Column).replace(Column(this="y"))
(COLUMN this: y)
>>> tree.sql()
'SELECT y FROM tbl'
Arguments:
  • expression (Expression|None): new node
Returns:

The new expression or expressions.

def pop(self):
566    def pop(self):
567        """
568        Remove this expression from its AST.
569
570        Returns:
571            The popped expression.
572        """
573        self.replace(None)
574        return self

Remove this expression from its AST.

Returns:

The popped expression.

def assert_is(self, type_):
576    def assert_is(self, type_):
577        """
578        Assert that this `Expression` is an instance of `type_`.
579
580        If it is NOT an instance of `type_`, this raises an assertion error.
581        Otherwise, this returns this expression.
582
583        Examples:
584            This is useful for type security in chained expressions:
585
586            >>> import sqlglot
587            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
588            'SELECT x, z FROM y'
589        """
590        assert isinstance(self, type_)
591        return self

Assert that this Expression is an instance of type_.

If it is NOT an instance of type_, this raises an assertion error. Otherwise, this returns this expression.

Examples:

This is useful for type security in chained expressions:

>>> import sqlglot
>>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
'SELECT x, z FROM y'
def error_messages(self, args: Optional[Sequence] = None) -> List[str]:
593    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
594        """
595        Checks if this expression is valid (e.g. all mandatory args are set).
596
597        Args:
598            args: a sequence of values that were used to instantiate a Func expression. This is used
599                to check that the provided arguments don't exceed the function argument limit.
600
601        Returns:
602            A list of error messages for all possible errors that were found.
603        """
604        errors: t.List[str] = []
605
606        for k in self.args:
607            if k not in self.arg_types:
608                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
609        for k, mandatory in self.arg_types.items():
610            v = self.args.get(k)
611            if mandatory and (v is None or (isinstance(v, list) and not v)):
612                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
613
614        if (
615            args
616            and isinstance(self, Func)
617            and len(args) > len(self.arg_types)
618            and not self.is_var_len_args
619        ):
620            errors.append(
621                f"The number of provided arguments ({len(args)}) is greater than "
622                f"the maximum number of supported arguments ({len(self.arg_types)})"
623            )
624
625        return errors

Checks if this expression is valid (e.g. all mandatory args are set).

Arguments:
  • args: a sequence of values that were used to instantiate a Func expression. This is used to check that the provided arguments don't exceed the function argument limit.
Returns:

A list of error messages for all possible errors that were found.

def dump(self):
627    def dump(self):
628        """
629        Dump this Expression to a JSON-serializable dict.
630        """
631        from sqlglot.serde import dump
632
633        return dump(self)

Dump this Expression to a JSON-serializable dict.

@classmethod
def load(cls, obj):
635    @classmethod
636    def load(cls, obj):
637        """
638        Load a dict (as returned by `Expression.dump`) into an Expression instance.
639        """
640        from sqlglot.serde import load
641
642        return load(obj)

Load a dict (as returned by Expression.dump) into an Expression instance.

class Condition(Expression):
653class Condition(Expression):
654    def and_(self, *expressions, dialect=None, **opts):
655        """
656        AND this condition with one or multiple expressions.
657
658        Example:
659            >>> condition("x=1").and_("y=1").sql()
660            'x = 1 AND y = 1'
661
662        Args:
663            *expressions (str | Expression): the SQL code strings to parse.
664                If an `Expression` instance is passed, it will be used as-is.
665            dialect (str): the dialect used to parse the input expression.
666            opts (kwargs): other options to use to parse the input expressions.
667
668        Returns:
669            And: the new condition.
670        """
671        return and_(self, *expressions, dialect=dialect, **opts)
672
673    def or_(self, *expressions, dialect=None, **opts):
674        """
675        OR this condition with one or multiple expressions.
676
677        Example:
678            >>> condition("x=1").or_("y=1").sql()
679            'x = 1 OR y = 1'
680
681        Args:
682            *expressions (str | Expression): the SQL code strings to parse.
683                If an `Expression` instance is passed, it will be used as-is.
684            dialect (str): the dialect used to parse the input expression.
685            opts (kwargs): other options to use to parse the input expressions.
686
687        Returns:
688            Or: the new condition.
689        """
690        return or_(self, *expressions, dialect=dialect, **opts)
691
692    def not_(self):
693        """
694        Wrap this condition with NOT.
695
696        Example:
697            >>> condition("x=1").not_().sql()
698            'NOT x = 1'
699
700        Returns:
701            Not: the new condition.
702        """
703        return not_(self)
def and_(self, *expressions, dialect=None, **opts):
654    def and_(self, *expressions, dialect=None, **opts):
655        """
656        AND this condition with one or multiple expressions.
657
658        Example:
659            >>> condition("x=1").and_("y=1").sql()
660            'x = 1 AND y = 1'
661
662        Args:
663            *expressions (str | Expression): the SQL code strings to parse.
664                If an `Expression` instance is passed, it will be used as-is.
665            dialect (str): the dialect used to parse the input expression.
666            opts (kwargs): other options to use to parse the input expressions.
667
668        Returns:
669            And: the new condition.
670        """
671        return and_(self, *expressions, dialect=dialect, **opts)

AND this condition with one or multiple expressions.

Example:
>>> condition("x=1").and_("y=1").sql()
'x = 1 AND y = 1'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

And: the new condition.

def or_(self, *expressions, dialect=None, **opts):
673    def or_(self, *expressions, dialect=None, **opts):
674        """
675        OR this condition with one or multiple expressions.
676
677        Example:
678            >>> condition("x=1").or_("y=1").sql()
679            'x = 1 OR y = 1'
680
681        Args:
682            *expressions (str | Expression): the SQL code strings to parse.
683                If an `Expression` instance is passed, it will be used as-is.
684            dialect (str): the dialect used to parse the input expression.
685            opts (kwargs): other options to use to parse the input expressions.
686
687        Returns:
688            Or: the new condition.
689        """
690        return or_(self, *expressions, dialect=dialect, **opts)

OR this condition with one or multiple expressions.

Example:
>>> condition("x=1").or_("y=1").sql()
'x = 1 OR y = 1'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Or: the new condition.

def not_(self):
692    def not_(self):
693        """
694        Wrap this condition with NOT.
695
696        Example:
697            >>> condition("x=1").not_().sql()
698            'NOT x = 1'
699
700        Returns:
701            Not: the new condition.
702        """
703        return not_(self)

Wrap this condition with NOT.

Example:
>>> condition("x=1").not_().sql()
'NOT x = 1'
Returns:

Not: the new condition.

class Predicate(Condition):
706class Predicate(Condition):
707    """Relationships like x = y, x > 1, x >= y."""

Relationships like x = y, x > 1, x >= y.

class DerivedTable(Expression):
710class DerivedTable(Expression):
711    @property
712    def alias_column_names(self):
713        table_alias = self.args.get("alias")
714        if not table_alias:
715            return []
716        column_list = table_alias.assert_is(TableAlias).args.get("columns") or []
717        return [c.name for c in column_list]
718
719    @property
720    def selects(self):
721        alias = self.args.get("alias")
722
723        if alias:
724            return alias.columns
725        return []
726
727    @property
728    def named_selects(self):
729        return [select.output_name for select in self.selects]
class Unionable(Expression):
732class Unionable(Expression):
733    def union(self, expression, distinct=True, dialect=None, **opts):
734        """
735        Builds a UNION expression.
736
737        Example:
738            >>> import sqlglot
739            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
740            'SELECT * FROM foo UNION SELECT * FROM bla'
741
742        Args:
743            expression (str | Expression): the SQL code string.
744                If an `Expression` instance is passed, it will be used as-is.
745            distinct (bool): set the DISTINCT flag if and only if this is true.
746            dialect (str): the dialect used to parse the input expression.
747            opts (kwargs): other options to use to parse the input expressions.
748        Returns:
749            Union: the Union expression.
750        """
751        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
752
753    def intersect(self, expression, distinct=True, dialect=None, **opts):
754        """
755        Builds an INTERSECT expression.
756
757        Example:
758            >>> import sqlglot
759            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
760            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
761
762        Args:
763            expression (str | Expression): the SQL code string.
764                If an `Expression` instance is passed, it will be used as-is.
765            distinct (bool): set the DISTINCT flag if and only if this is true.
766            dialect (str): the dialect used to parse the input expression.
767            opts (kwargs): other options to use to parse the input expressions.
768        Returns:
769            Intersect: the Intersect expression
770        """
771        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
772
773    def except_(self, expression, distinct=True, dialect=None, **opts):
774        """
775        Builds an EXCEPT expression.
776
777        Example:
778            >>> import sqlglot
779            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
780            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
781
782        Args:
783            expression (str | Expression): the SQL code string.
784                If an `Expression` instance is passed, it will be used as-is.
785            distinct (bool): set the DISTINCT flag if and only if this is true.
786            dialect (str): the dialect used to parse the input expression.
787            opts (kwargs): other options to use to parse the input expressions.
788        Returns:
789            Except: the Except expression
790        """
791        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
def union(self, expression, distinct=True, dialect=None, **opts):
733    def union(self, expression, distinct=True, dialect=None, **opts):
734        """
735        Builds a UNION expression.
736
737        Example:
738            >>> import sqlglot
739            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
740            'SELECT * FROM foo UNION SELECT * FROM bla'
741
742        Args:
743            expression (str | Expression): the SQL code string.
744                If an `Expression` instance is passed, it will be used as-is.
745            distinct (bool): set the DISTINCT flag if and only if this is true.
746            dialect (str): the dialect used to parse the input expression.
747            opts (kwargs): other options to use to parse the input expressions.
748        Returns:
749            Union: the Union expression.
750        """
751        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds a UNION expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • expression (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Union: the Union expression.

def intersect(self, expression, distinct=True, dialect=None, **opts):
753    def intersect(self, expression, distinct=True, dialect=None, **opts):
754        """
755        Builds an INTERSECT expression.
756
757        Example:
758            >>> import sqlglot
759            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
760            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
761
762        Args:
763            expression (str | Expression): the SQL code string.
764                If an `Expression` instance is passed, it will be used as-is.
765            distinct (bool): set the DISTINCT flag if and only if this is true.
766            dialect (str): the dialect used to parse the input expression.
767            opts (kwargs): other options to use to parse the input expressions.
768        Returns:
769            Intersect: the Intersect expression
770        """
771        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an INTERSECT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • expression (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Intersect: the Intersect expression

def except_(self, expression, distinct=True, dialect=None, **opts):
773    def except_(self, expression, distinct=True, dialect=None, **opts):
774        """
775        Builds an EXCEPT expression.
776
777        Example:
778            >>> import sqlglot
779            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
780            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
781
782        Args:
783            expression (str | Expression): the SQL code string.
784                If an `Expression` instance is passed, it will be used as-is.
785            distinct (bool): set the DISTINCT flag if and only if this is true.
786            dialect (str): the dialect used to parse the input expression.
787            opts (kwargs): other options to use to parse the input expressions.
788        Returns:
789            Except: the Except expression
790        """
791        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an EXCEPT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • expression (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Except: the Except expression

class UDTF(DerivedTable, Unionable):
794class UDTF(DerivedTable, Unionable):
795    pass
class Cache(Expression):
798class Cache(Expression):
799    arg_types = {
800        "with": False,
801        "this": True,
802        "lazy": False,
803        "options": False,
804        "expression": False,
805    }
class Uncache(Expression):
808class Uncache(Expression):
809    arg_types = {"this": True, "exists": False}
class Create(Expression):
812class Create(Expression):
813    arg_types = {
814        "with": False,
815        "this": True,
816        "kind": True,
817        "expression": False,
818        "exists": False,
819        "properties": False,
820        "replace": False,
821        "unique": False,
822        "indexes": False,
823        "no_schema_binding": False,
824        "begin": False,
825    }
class Describe(Expression):
828class Describe(Expression):
829    arg_types = {"this": True, "kind": False}
class Pragma(Expression):
832class Pragma(Expression):
833    pass
class Set(Expression):
836class Set(Expression):
837    arg_types = {"expressions": False}
class SetItem(Expression):
840class SetItem(Expression):
841    arg_types = {
842        "this": False,
843        "expressions": False,
844        "kind": False,
845        "collate": False,  # MySQL SET NAMES statement
846        "global": False,
847    }
class Show(Expression):
850class Show(Expression):
851    arg_types = {
852        "this": True,
853        "target": False,
854        "offset": False,
855        "limit": False,
856        "like": False,
857        "where": False,
858        "db": False,
859        "full": False,
860        "mutex": False,
861        "query": False,
862        "channel": False,
863        "global": False,
864        "log": False,
865        "position": False,
866        "types": False,
867    }
class UserDefinedFunction(Expression):
870class UserDefinedFunction(Expression):
871    arg_types = {"this": True, "expressions": False, "wrapped": False}
class CharacterSet(Expression):
874class CharacterSet(Expression):
875    arg_types = {"this": True, "default": False}
class With(Expression):
878class With(Expression):
879    arg_types = {"expressions": True, "recursive": False}
880
881    @property
882    def recursive(self) -> bool:
883        return bool(self.args.get("recursive"))
class WithinGroup(Expression):
886class WithinGroup(Expression):
887    arg_types = {"this": True, "expression": False}
class CTE(DerivedTable):
890class CTE(DerivedTable):
891    arg_types = {"this": True, "alias": True}
class TableAlias(Expression):
894class TableAlias(Expression):
895    arg_types = {"this": False, "columns": False}
896
897    @property
898    def columns(self):
899        return self.args.get("columns") or []
class BitString(Condition):
902class BitString(Condition):
903    pass
class HexString(Condition):
906class HexString(Condition):
907    pass
class ByteString(Condition):
910class ByteString(Condition):
911    pass
class Column(Condition):
914class Column(Condition):
915    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
916
917    @property
918    def table(self) -> str:
919        return self.text("table")
920
921    @property
922    def db(self) -> str:
923        return self.text("db")
924
925    @property
926    def catalog(self) -> str:
927        return self.text("catalog")
928
929    @property
930    def output_name(self) -> str:
931        return self.name
932
933    @property
934    def parts(self) -> t.List[Identifier]:
935        """Return the parts of a column in order catalog, db, table, name."""
936        return [part for part in reversed(list(self.args.values())) if part]
937
938    def to_dot(self) -> Dot:
939        """Converts the column into a dot expression."""
940        parts = self.parts
941        parent = self.parent
942
943        while parent:
944            if isinstance(parent, Dot):
945                parts.append(parent.expression)
946            parent = parent.parent
947
948        return Dot.build(parts)
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''

Return the parts of a column in order catalog, db, table, name.

def to_dot(self) -> sqlglot.expressions.Dot:
938    def to_dot(self) -> Dot:
939        """Converts the column into a dot expression."""
940        parts = self.parts
941        parent = self.parent
942
943        while parent:
944            if isinstance(parent, Dot):
945                parts.append(parent.expression)
946            parent = parent.parent
947
948        return Dot.build(parts)

Converts the column into a dot expression.

class ColumnPosition(Expression):
951class ColumnPosition(Expression):
952    arg_types = {"this": False, "position": True}
class ColumnDef(Expression):
955class ColumnDef(Expression):
956    arg_types = {
957        "this": True,
958        "kind": False,
959        "constraints": False,
960        "exists": False,
961        "position": False,
962    }
class AlterColumn(Expression):
965class AlterColumn(Expression):
966    arg_types = {
967        "this": True,
968        "dtype": False,
969        "collate": False,
970        "using": False,
971        "default": False,
972        "drop": False,
973    }
class RenameTable(Expression):
976class RenameTable(Expression):
977    pass
class SetTag(Expression):
980class SetTag(Expression):
981    arg_types = {"expressions": True, "unset": False}
class Comment(Expression):
984class Comment(Expression):
985    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
class ColumnConstraint(Expression):
988class ColumnConstraint(Expression):
989    arg_types = {"this": False, "kind": True}
class ColumnConstraintKind(Expression):
992class ColumnConstraintKind(Expression):
993    pass
class AutoIncrementColumnConstraint(ColumnConstraintKind):
996class AutoIncrementColumnConstraint(ColumnConstraintKind):
997    pass
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1000class CaseSpecificColumnConstraint(ColumnConstraintKind):
1001    arg_types = {"not_": True}
class CharacterSetColumnConstraint(ColumnConstraintKind):
1004class CharacterSetColumnConstraint(ColumnConstraintKind):
1005    arg_types = {"this": True}
class CheckColumnConstraint(ColumnConstraintKind):
1008class CheckColumnConstraint(ColumnConstraintKind):
1009    pass
class CollateColumnConstraint(ColumnConstraintKind):
1012class CollateColumnConstraint(ColumnConstraintKind):
1013    pass
class CommentColumnConstraint(ColumnConstraintKind):
1016class CommentColumnConstraint(ColumnConstraintKind):
1017    pass
class CompressColumnConstraint(ColumnConstraintKind):
1020class CompressColumnConstraint(ColumnConstraintKind):
1021    pass
class DateFormatColumnConstraint(ColumnConstraintKind):
1024class DateFormatColumnConstraint(ColumnConstraintKind):
1025    arg_types = {"this": True}
class DefaultColumnConstraint(ColumnConstraintKind):
1028class DefaultColumnConstraint(ColumnConstraintKind):
1029    pass
class EncodeColumnConstraint(ColumnConstraintKind):
1032class EncodeColumnConstraint(ColumnConstraintKind):
1033    pass
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1036class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1037    # this: True -> ALWAYS, this: False -> BY DEFAULT
1038    arg_types = {
1039        "this": False,
1040        "start": False,
1041        "increment": False,
1042        "minvalue": False,
1043        "maxvalue": False,
1044        "cycle": False,
1045    }
class InlineLengthColumnConstraint(ColumnConstraintKind):
1048class InlineLengthColumnConstraint(ColumnConstraintKind):
1049    pass
class NotNullColumnConstraint(ColumnConstraintKind):
1052class NotNullColumnConstraint(ColumnConstraintKind):
1053    arg_types = {"allow_null": False}
class OnUpdateColumnConstraint(ColumnConstraintKind):
1057class OnUpdateColumnConstraint(ColumnConstraintKind):
1058    pass
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1061class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1062    arg_types = {"desc": False}
class TitleColumnConstraint(ColumnConstraintKind):
1065class TitleColumnConstraint(ColumnConstraintKind):
1066    pass
class UniqueColumnConstraint(ColumnConstraintKind):
1069class UniqueColumnConstraint(ColumnConstraintKind):
1070    arg_types: t.Dict[str, t.Any] = {}
class UppercaseColumnConstraint(ColumnConstraintKind):
1073class UppercaseColumnConstraint(ColumnConstraintKind):
1074    arg_types: t.Dict[str, t.Any] = {}
class PathColumnConstraint(ColumnConstraintKind):
1077class PathColumnConstraint(ColumnConstraintKind):
1078    pass
class Constraint(Expression):
1081class Constraint(Expression):
1082    arg_types = {"this": True, "expressions": True}
class Delete(Expression):
1085class Delete(Expression):
1086    arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False}
1087
1088    def delete(
1089        self,
1090        table: ExpOrStr,
1091        dialect: DialectType = None,
1092        copy: bool = True,
1093        **opts,
1094    ) -> Delete:
1095        """
1096        Create a DELETE expression or replace the table on an existing DELETE expression.
1097
1098        Example:
1099            >>> delete("tbl").sql()
1100            'DELETE FROM tbl'
1101
1102        Args:
1103            table: the table from which to delete.
1104            dialect: the dialect used to parse the input expression.
1105            copy: if `False`, modify this expression instance in-place.
1106            opts: other options to use to parse the input expressions.
1107
1108        Returns:
1109            Delete: the modified expression.
1110        """
1111        return _apply_builder(
1112            expression=table,
1113            instance=self,
1114            arg="this",
1115            dialect=dialect,
1116            into=Table,
1117            copy=copy,
1118            **opts,
1119        )
1120
1121    def where(
1122        self,
1123        *expressions: ExpOrStr,
1124        append: bool = True,
1125        dialect: DialectType = None,
1126        copy: bool = True,
1127        **opts,
1128    ) -> Delete:
1129        """
1130        Append to or set the WHERE expressions.
1131
1132        Example:
1133            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1134            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1135
1136        Args:
1137            *expressions: the SQL code strings to parse.
1138                If an `Expression` instance is passed, it will be used as-is.
1139                Multiple expressions are combined with an AND operator.
1140            append: if `True`, AND the new expressions to any existing expression.
1141                Otherwise, this resets the expression.
1142            dialect: the dialect used to parse the input expressions.
1143            copy: if `False`, modify this expression instance in-place.
1144            opts: other options to use to parse the input expressions.
1145
1146        Returns:
1147            Delete: the modified expression.
1148        """
1149        return _apply_conjunction_builder(
1150            *expressions,
1151            instance=self,
1152            arg="where",
1153            append=append,
1154            into=Where,
1155            dialect=dialect,
1156            copy=copy,
1157            **opts,
1158        )
1159
1160    def returning(
1161        self,
1162        expression: ExpOrStr,
1163        dialect: DialectType = None,
1164        copy: bool = True,
1165        **opts,
1166    ) -> Delete:
1167        """
1168        Set the RETURNING expression. Not supported by all dialects.
1169
1170        Example:
1171            >>> delete("tbl").returning("*", dialect="postgres").sql()
1172            'DELETE FROM tbl RETURNING *'
1173
1174        Args:
1175            expression: the SQL code strings to parse.
1176                If an `Expression` instance is passed, it will be used as-is.
1177            dialect: the dialect used to parse the input expressions.
1178            copy: if `False`, modify this expression instance in-place.
1179            opts: other options to use to parse the input expressions.
1180
1181        Returns:
1182            Delete: the modified expression.
1183        """
1184        return _apply_builder(
1185            expression=expression,
1186            instance=self,
1187            arg="returning",
1188            prefix="RETURNING",
1189            dialect=dialect,
1190            copy=copy,
1191            into=Returning,
1192            **opts,
1193        )
def delete( self, table: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1088    def delete(
1089        self,
1090        table: ExpOrStr,
1091        dialect: DialectType = None,
1092        copy: bool = True,
1093        **opts,
1094    ) -> Delete:
1095        """
1096        Create a DELETE expression or replace the table on an existing DELETE expression.
1097
1098        Example:
1099            >>> delete("tbl").sql()
1100            'DELETE FROM tbl'
1101
1102        Args:
1103            table: the table from which to delete.
1104            dialect: the dialect used to parse the input expression.
1105            copy: if `False`, modify this expression instance in-place.
1106            opts: other options to use to parse the input expressions.
1107
1108        Returns:
1109            Delete: the modified expression.
1110        """
1111        return _apply_builder(
1112            expression=table,
1113            instance=self,
1114            arg="this",
1115            dialect=dialect,
1116            into=Table,
1117            copy=copy,
1118            **opts,
1119        )

Create a DELETE expression or replace the table on an existing DELETE expression.

Example:
>>> delete("tbl").sql()
'DELETE FROM tbl'
Arguments:
  • table: the table from which to delete.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def where( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1121    def where(
1122        self,
1123        *expressions: ExpOrStr,
1124        append: bool = True,
1125        dialect: DialectType = None,
1126        copy: bool = True,
1127        **opts,
1128    ) -> Delete:
1129        """
1130        Append to or set the WHERE expressions.
1131
1132        Example:
1133            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1134            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1135
1136        Args:
1137            *expressions: the SQL code strings to parse.
1138                If an `Expression` instance is passed, it will be used as-is.
1139                Multiple expressions are combined with an AND operator.
1140            append: if `True`, AND the new expressions to any existing expression.
1141                Otherwise, this resets the expression.
1142            dialect: the dialect used to parse the input expressions.
1143            copy: if `False`, modify this expression instance in-place.
1144            opts: other options to use to parse the input expressions.
1145
1146        Returns:
1147            Delete: the modified expression.
1148        """
1149        return _apply_conjunction_builder(
1150            *expressions,
1151            instance=self,
1152            arg="where",
1153            append=append,
1154            into=Where,
1155            dialect=dialect,
1156            copy=copy,
1157            **opts,
1158        )

Append to or set the WHERE expressions.

Example:
>>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
"DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def returning( self, expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1160    def returning(
1161        self,
1162        expression: ExpOrStr,
1163        dialect: DialectType = None,
1164        copy: bool = True,
1165        **opts,
1166    ) -> Delete:
1167        """
1168        Set the RETURNING expression. Not supported by all dialects.
1169
1170        Example:
1171            >>> delete("tbl").returning("*", dialect="postgres").sql()
1172            'DELETE FROM tbl RETURNING *'
1173
1174        Args:
1175            expression: the SQL code strings to parse.
1176                If an `Expression` instance is passed, it will be used as-is.
1177            dialect: the dialect used to parse the input expressions.
1178            copy: if `False`, modify this expression instance in-place.
1179            opts: other options to use to parse the input expressions.
1180
1181        Returns:
1182            Delete: the modified expression.
1183        """
1184        return _apply_builder(
1185            expression=expression,
1186            instance=self,
1187            arg="returning",
1188            prefix="RETURNING",
1189            dialect=dialect,
1190            copy=copy,
1191            into=Returning,
1192            **opts,
1193        )

Set the RETURNING expression. Not supported by all dialects.

Example:
>>> delete("tbl").returning("*", dialect="postgres").sql()
'DELETE FROM tbl RETURNING *'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

class Drop(Expression):
1196class Drop(Expression):
1197    arg_types = {
1198        "this": False,
1199        "kind": False,
1200        "exists": False,
1201        "temporary": False,
1202        "materialized": False,
1203        "cascade": False,
1204        "constraints": False,
1205        "purge": False,
1206    }
class Filter(Expression):
1209class Filter(Expression):
1210    arg_types = {"this": True, "expression": True}
class Check(Expression):
1213class Check(Expression):
1214    pass
class Directory(Expression):
1217class Directory(Expression):
1218    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1219    arg_types = {"this": True, "local": False, "row_format": False}
class ForeignKey(Expression):
1222class ForeignKey(Expression):
1223    arg_types = {
1224        "expressions": True,
1225        "reference": False,
1226        "delete": False,
1227        "update": False,
1228    }
class PrimaryKey(Expression):
1231class PrimaryKey(Expression):
1232    arg_types = {"expressions": True, "options": False}
class Unique(Expression):
1235class Unique(Expression):
1236    arg_types = {"expressions": True}
class Into(Expression):
1241class Into(Expression):
1242    arg_types = {"this": True, "temporary": False, "unlogged": False}
class From(Expression):
1245class From(Expression):
1246    arg_types = {"expressions": True}
class Having(Expression):
1249class Having(Expression):
1250    pass
class Hint(Expression):
1253class Hint(Expression):
1254    arg_types = {"expressions": True}
class JoinHint(Expression):
1257class JoinHint(Expression):
1258    arg_types = {"this": True, "expressions": True}
class Identifier(Expression):
1261class Identifier(Expression):
1262    arg_types = {"this": True, "quoted": False}
1263
1264    @property
1265    def quoted(self):
1266        return bool(self.args.get("quoted"))
1267
1268    @property
1269    def hashable_args(self) -> t.Any:
1270        if self.quoted and any(char.isupper() for char in self.this):
1271            return (self.this, self.quoted)
1272        return self.this.lower()
1273
1274    @property
1275    def output_name(self):
1276        return self.name
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Index(Expression):
1279class Index(Expression):
1280    arg_types = {
1281        "this": False,
1282        "table": False,
1283        "where": False,
1284        "columns": False,
1285        "unique": False,
1286        "primary": False,
1287        "amp": False,  # teradata
1288    }
class Insert(Expression):
1291class Insert(Expression):
1292    arg_types = {
1293        "with": False,
1294        "this": True,
1295        "expression": False,
1296        "returning": False,
1297        "overwrite": False,
1298        "exists": False,
1299        "partition": False,
1300        "alternative": False,
1301    }
class Returning(Expression):
1304class Returning(Expression):
1305    arg_types = {"expressions": True}
class Introducer(Expression):
1309class Introducer(Expression):
1310    arg_types = {"this": True, "expression": True}
class National(Expression):
1314class National(Expression):
1315    pass
class LoadData(Expression):
1318class LoadData(Expression):
1319    arg_types = {
1320        "this": True,
1321        "local": False,
1322        "overwrite": False,
1323        "inpath": True,
1324        "partition": False,
1325        "input_format": False,
1326        "serde": False,
1327    }
class Partition(Expression):
1330class Partition(Expression):
1331    arg_types = {"expressions": True}
class Fetch(Expression):
1334class Fetch(Expression):
1335    arg_types = {
1336        "direction": False,
1337        "count": False,
1338        "percent": False,
1339        "with_ties": False,
1340    }
class Group(Expression):
1343class Group(Expression):
1344    arg_types = {
1345        "expressions": False,
1346        "grouping_sets": False,
1347        "cube": False,
1348        "rollup": False,
1349    }
class Lambda(Expression):
1352class Lambda(Expression):
1353    arg_types = {"this": True, "expressions": True}
class Limit(Expression):
1356class Limit(Expression):
1357    arg_types = {"this": False, "expression": True}
class Literal(Condition):
1360class Literal(Condition):
1361    arg_types = {"this": True, "is_string": True}
1362
1363    @property
1364    def hashable_args(self) -> t.Any:
1365        return (self.this, self.args.get("is_string"))
1366
1367    @classmethod
1368    def number(cls, number) -> Literal:
1369        return cls(this=str(number), is_string=False)
1370
1371    @classmethod
1372    def string(cls, string) -> Literal:
1373        return cls(this=str(string), is_string=True)
1374
1375    @property
1376    def output_name(self):
1377        return self.name
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1367    @classmethod
1368    def number(cls, number) -> Literal:
1369        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1371    @classmethod
1372    def string(cls, string) -> Literal:
1373        return cls(this=str(string), is_string=True)
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Join(Expression):
1380class Join(Expression):
1381    arg_types = {
1382        "this": True,
1383        "on": False,
1384        "side": False,
1385        "kind": False,
1386        "using": False,
1387        "natural": False,
1388        "hint": False,
1389    }
1390
1391    @property
1392    def kind(self):
1393        return self.text("kind").upper()
1394
1395    @property
1396    def side(self):
1397        return self.text("side").upper()
1398
1399    @property
1400    def hint(self):
1401        return self.text("hint").upper()
1402
1403    @property
1404    def alias_or_name(self):
1405        return self.this.alias_or_name
1406
1407    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1408        """
1409        Append to or set the ON expressions.
1410
1411        Example:
1412            >>> import sqlglot
1413            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1414            'JOIN x ON y = 1'
1415
1416        Args:
1417            *expressions (str | Expression): the SQL code strings to parse.
1418                If an `Expression` instance is passed, it will be used as-is.
1419                Multiple expressions are combined with an AND operator.
1420            append (bool): if `True`, AND the new expressions to any existing expression.
1421                Otherwise, this resets the expression.
1422            dialect (str): the dialect used to parse the input expressions.
1423            copy (bool): if `False`, modify this expression instance in-place.
1424            opts (kwargs): other options to use to parse the input expressions.
1425
1426        Returns:
1427            Join: the modified join expression.
1428        """
1429        join = _apply_conjunction_builder(
1430            *expressions,
1431            instance=self,
1432            arg="on",
1433            append=append,
1434            dialect=dialect,
1435            copy=copy,
1436            **opts,
1437        )
1438
1439        if join.kind == "CROSS":
1440            join.set("kind", None)
1441
1442        return join
1443
1444    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1445        """
1446        Append to or set the USING expressions.
1447
1448        Example:
1449            >>> import sqlglot
1450            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1451            'JOIN x USING (foo, bla)'
1452
1453        Args:
1454            *expressions (str | Expression): the SQL code strings to parse.
1455                If an `Expression` instance is passed, it will be used as-is.
1456            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1457                Otherwise, this resets the expression.
1458            dialect (str): the dialect used to parse the input expressions.
1459            copy (bool): if `False`, modify this expression instance in-place.
1460            opts (kwargs): other options to use to parse the input expressions.
1461
1462        Returns:
1463            Join: the modified join expression.
1464        """
1465        join = _apply_list_builder(
1466            *expressions,
1467            instance=self,
1468            arg="using",
1469            append=append,
1470            dialect=dialect,
1471            copy=copy,
1472            **opts,
1473        )
1474
1475        if join.kind == "CROSS":
1476            join.set("kind", None)
1477
1478        return join
def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1407    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1408        """
1409        Append to or set the ON expressions.
1410
1411        Example:
1412            >>> import sqlglot
1413            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1414            'JOIN x ON y = 1'
1415
1416        Args:
1417            *expressions (str | Expression): the SQL code strings to parse.
1418                If an `Expression` instance is passed, it will be used as-is.
1419                Multiple expressions are combined with an AND operator.
1420            append (bool): if `True`, AND the new expressions to any existing expression.
1421                Otherwise, this resets the expression.
1422            dialect (str): the dialect used to parse the input expressions.
1423            copy (bool): if `False`, modify this expression instance in-place.
1424            opts (kwargs): other options to use to parse the input expressions.
1425
1426        Returns:
1427            Join: the modified join expression.
1428        """
1429        join = _apply_conjunction_builder(
1430            *expressions,
1431            instance=self,
1432            arg="on",
1433            append=append,
1434            dialect=dialect,
1435            copy=copy,
1436            **opts,
1437        )
1438
1439        if join.kind == "CROSS":
1440            join.set("kind", None)
1441
1442        return join

Append to or set the ON expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
'JOIN x ON y = 1'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Join: the modified join expression.

def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1444    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1445        """
1446        Append to or set the USING expressions.
1447
1448        Example:
1449            >>> import sqlglot
1450            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1451            'JOIN x USING (foo, bla)'
1452
1453        Args:
1454            *expressions (str | Expression): the SQL code strings to parse.
1455                If an `Expression` instance is passed, it will be used as-is.
1456            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1457                Otherwise, this resets the expression.
1458            dialect (str): the dialect used to parse the input expressions.
1459            copy (bool): if `False`, modify this expression instance in-place.
1460            opts (kwargs): other options to use to parse the input expressions.
1461
1462        Returns:
1463            Join: the modified join expression.
1464        """
1465        join = _apply_list_builder(
1466            *expressions,
1467            instance=self,
1468            arg="using",
1469            append=append,
1470            dialect=dialect,
1471            copy=copy,
1472            **opts,
1473        )
1474
1475        if join.kind == "CROSS":
1476            join.set("kind", None)
1477
1478        return join

Append to or set the USING expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
'JOIN x USING (foo, bla)'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, concatenate the new expressions to the existing "using" list. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Join: the modified join expression.

class Lateral(UDTF):
1481class Lateral(UDTF):
1482    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
class MatchRecognize(Expression):
1485class MatchRecognize(Expression):
1486    arg_types = {
1487        "partition_by": False,
1488        "order": False,
1489        "measures": False,
1490        "rows": False,
1491        "after": False,
1492        "pattern": False,
1493        "define": False,
1494        "alias": False,
1495    }
class Final(Expression):
1500class Final(Expression):
1501    pass
class Offset(Expression):
1504class Offset(Expression):
1505    arg_types = {"this": False, "expression": True}
class Order(Expression):
1508class Order(Expression):
1509    arg_types = {"this": False, "expressions": True}
class Cluster(Order):
1514class Cluster(Order):
1515    pass
class Distribute(Order):
1518class Distribute(Order):
1519    pass
class Sort(Order):
1522class Sort(Order):
1523    pass
class Ordered(Expression):
1526class Ordered(Expression):
1527    arg_types = {"this": True, "desc": True, "nulls_first": True}
class Property(Expression):
1530class Property(Expression):
1531    arg_types = {"this": True, "value": True}
class AfterJournalProperty(Property):
1534class AfterJournalProperty(Property):
1535    arg_types = {"no": True, "dual": False, "local": False}
class AlgorithmProperty(Property):
1538class AlgorithmProperty(Property):
1539    arg_types = {"this": True}
class AutoIncrementProperty(Property):
1542class AutoIncrementProperty(Property):
1543    arg_types = {"this": True}
class BlockCompressionProperty(Property):
1546class BlockCompressionProperty(Property):
1547    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
class CharacterSetProperty(Property):
1550class CharacterSetProperty(Property):
1551    arg_types = {"this": True, "default": True}
class ChecksumProperty(Property):
1554class ChecksumProperty(Property):
1555    arg_types = {"on": False, "default": False}
class CollateProperty(Property):
1558class CollateProperty(Property):
1559    arg_types = {"this": True}
class DataBlocksizeProperty(Property):
1562class DataBlocksizeProperty(Property):
1563    arg_types = {"size": False, "units": False, "min": False, "default": False}
class DefinerProperty(Property):
1566class DefinerProperty(Property):
1567    arg_types = {"this": True}
class DistKeyProperty(Property):
1570class DistKeyProperty(Property):
1571    arg_types = {"this": True}
class DistStyleProperty(Property):
1574class DistStyleProperty(Property):
1575    arg_types = {"this": True}
class EngineProperty(Property):
1578class EngineProperty(Property):
1579    arg_types = {"this": True}
class ExecuteAsProperty(Property):
1582class ExecuteAsProperty(Property):
1583    arg_types = {"this": True}
class ExternalProperty(Property):
1586class ExternalProperty(Property):
1587    arg_types = {"this": False}
class FallbackProperty(Property):
1590class FallbackProperty(Property):
1591    arg_types = {"no": True, "protection": False}
class FileFormatProperty(Property):
1594class FileFormatProperty(Property):
1595    arg_types = {"this": True}
class FreespaceProperty(Property):
1598class FreespaceProperty(Property):
1599    arg_types = {"this": True, "percent": False}
class InputOutputFormat(Expression):
1602class InputOutputFormat(Expression):
1603    arg_types = {"input_format": False, "output_format": False}
class IsolatedLoadingProperty(Property):
1606class IsolatedLoadingProperty(Property):
1607    arg_types = {
1608        "no": True,
1609        "concurrent": True,
1610        "for_all": True,
1611        "for_insert": True,
1612        "for_none": True,
1613    }
class JournalProperty(Property):
1616class JournalProperty(Property):
1617    arg_types = {"no": True, "dual": False, "before": False}
class LanguageProperty(Property):
1620class LanguageProperty(Property):
1621    arg_types = {"this": True}
class LikeProperty(Property):
1624class LikeProperty(Property):
1625    arg_types = {"this": True, "expressions": False}
class LocationProperty(Property):
1628class LocationProperty(Property):
1629    arg_types = {"this": True}
class LockingProperty(Property):
1632class LockingProperty(Property):
1633    arg_types = {
1634        "this": False,
1635        "kind": True,
1636        "for_or_in": True,
1637        "lock_type": True,
1638        "override": False,
1639    }
class LogProperty(Property):
1642class LogProperty(Property):
1643    arg_types = {"no": True}
class MaterializedProperty(Property):
1646class MaterializedProperty(Property):
1647    arg_types = {"this": False}
class MergeBlockRatioProperty(Property):
1650class MergeBlockRatioProperty(Property):
1651    arg_types = {"this": False, "no": False, "default": False, "percent": False}
class NoPrimaryIndexProperty(Property):
1654class NoPrimaryIndexProperty(Property):
1655    arg_types = {"this": False}
class OnCommitProperty(Property):
1658class OnCommitProperty(Property):
1659    arg_type = {"this": False}
class PartitionedByProperty(Property):
1662class PartitionedByProperty(Property):
1663    arg_types = {"this": True}
class ReturnsProperty(Property):
1666class ReturnsProperty(Property):
1667    arg_types = {"this": True, "is_table": False, "table": False}
class RowFormatProperty(Property):
1670class RowFormatProperty(Property):
1671    arg_types = {"this": True}
class RowFormatDelimitedProperty(Property):
1674class RowFormatDelimitedProperty(Property):
1675    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
1676    arg_types = {
1677        "fields": False,
1678        "escaped": False,
1679        "collection_items": False,
1680        "map_keys": False,
1681        "lines": False,
1682        "null": False,
1683        "serde": False,
1684    }
class RowFormatSerdeProperty(Property):
1687class RowFormatSerdeProperty(Property):
1688    arg_types = {"this": True}
class SchemaCommentProperty(Property):
1691class SchemaCommentProperty(Property):
1692    arg_types = {"this": True}
class SerdeProperties(Property):
1695class SerdeProperties(Property):
1696    arg_types = {"expressions": True}
class SetProperty(Property):
1699class SetProperty(Property):
1700    arg_types = {"multi": True}
class SortKeyProperty(Property):
1703class SortKeyProperty(Property):
1704    arg_types = {"this": True, "compound": False}
class SqlSecurityProperty(Property):
1707class SqlSecurityProperty(Property):
1708    arg_types = {"definer": True}
class StabilityProperty(Property):
1711class StabilityProperty(Property):
1712    arg_types = {"this": True}
class TableFormatProperty(Property):
1715class TableFormatProperty(Property):
1716    arg_types = {"this": True}
class TemporaryProperty(Property):
1719class TemporaryProperty(Property):
1720    arg_types = {"global_": True}
class TransientProperty(Property):
1723class TransientProperty(Property):
1724    arg_types = {"this": False}
class VolatileProperty(Property):
1727class VolatileProperty(Property):
1728    arg_types = {"this": False}
class WithDataProperty(Property):
1731class WithDataProperty(Property):
1732    arg_types = {"no": True, "statistics": False}
class WithJournalTableProperty(Property):
1735class WithJournalTableProperty(Property):
1736    arg_types = {"this": True}
class Properties(Expression):
1739class Properties(Expression):
1740    arg_types = {"expressions": True}
1741
1742    NAME_TO_PROPERTY = {
1743        "ALGORITHM": AlgorithmProperty,
1744        "AUTO_INCREMENT": AutoIncrementProperty,
1745        "CHARACTER SET": CharacterSetProperty,
1746        "COLLATE": CollateProperty,
1747        "COMMENT": SchemaCommentProperty,
1748        "DEFINER": DefinerProperty,
1749        "DISTKEY": DistKeyProperty,
1750        "DISTSTYLE": DistStyleProperty,
1751        "ENGINE": EngineProperty,
1752        "EXECUTE AS": ExecuteAsProperty,
1753        "FORMAT": FileFormatProperty,
1754        "LANGUAGE": LanguageProperty,
1755        "LOCATION": LocationProperty,
1756        "PARTITIONED_BY": PartitionedByProperty,
1757        "RETURNS": ReturnsProperty,
1758        "ROW_FORMAT": RowFormatProperty,
1759        "SORTKEY": SortKeyProperty,
1760        "TABLE_FORMAT": TableFormatProperty,
1761    }
1762
1763    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
1764
1765    # CREATE property locations
1766    # Form: schema specified
1767    #   create [POST_CREATE]
1768    #     table a [POST_NAME]
1769    #     (b int) [POST_SCHEMA]
1770    #     with ([POST_WITH])
1771    #     index (b) [POST_INDEX]
1772    #
1773    # Form: alias selection
1774    #   create [POST_CREATE]
1775    #     table a [POST_NAME]
1776    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
1777    #     index (c) [POST_INDEX]
1778    class Location(AutoName):
1779        POST_CREATE = auto()
1780        POST_NAME = auto()
1781        POST_SCHEMA = auto()
1782        POST_WITH = auto()
1783        POST_ALIAS = auto()
1784        POST_EXPRESSION = auto()
1785        POST_INDEX = auto()
1786        UNSUPPORTED = auto()
1787
1788    @classmethod
1789    def from_dict(cls, properties_dict) -> Properties:
1790        expressions = []
1791        for key, value in properties_dict.items():
1792            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1793            if property_cls:
1794                expressions.append(property_cls(this=convert(value)))
1795            else:
1796                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1797
1798        return cls(expressions=expressions)
@classmethod
def from_dict(cls, properties_dict) -> sqlglot.expressions.Properties:
1788    @classmethod
1789    def from_dict(cls, properties_dict) -> Properties:
1790        expressions = []
1791        for key, value in properties_dict.items():
1792            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1793            if property_cls:
1794                expressions.append(property_cls(this=convert(value)))
1795            else:
1796                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1797
1798        return cls(expressions=expressions)
class Properties.Location(sqlglot.helper.AutoName):
1778    class Location(AutoName):
1779        POST_CREATE = auto()
1780        POST_NAME = auto()
1781        POST_SCHEMA = auto()
1782        POST_WITH = auto()
1783        POST_ALIAS = auto()
1784        POST_EXPRESSION = auto()
1785        POST_INDEX = auto()
1786        UNSUPPORTED = auto()

An enumeration.

POST_CREATE = <Location.POST_CREATE: 'POST_CREATE'>
POST_NAME = <Location.POST_NAME: 'POST_NAME'>
POST_SCHEMA = <Location.POST_SCHEMA: 'POST_SCHEMA'>
POST_WITH = <Location.POST_WITH: 'POST_WITH'>
POST_ALIAS = <Location.POST_ALIAS: 'POST_ALIAS'>
POST_EXPRESSION = <Location.POST_EXPRESSION: 'POST_EXPRESSION'>
POST_INDEX = <Location.POST_INDEX: 'POST_INDEX'>
UNSUPPORTED = <Location.UNSUPPORTED: 'UNSUPPORTED'>
Inherited Members
enum.Enum
name
value
class Qualify(Expression):
1801class Qualify(Expression):
1802    pass
class Return(Expression):
1806class Return(Expression):
1807    pass
class Reference(Expression):
1810class Reference(Expression):
1811    arg_types = {"this": True, "expressions": False, "options": False}
class Tuple(Expression):
1814class Tuple(Expression):
1815    arg_types = {"expressions": False}
class Subqueryable(Unionable):
1818class Subqueryable(Unionable):
1819    def subquery(self, alias=None, copy=True) -> Subquery:
1820        """
1821        Convert this expression to an aliased expression that can be used as a Subquery.
1822
1823        Example:
1824            >>> subquery = Select().select("x").from_("tbl").subquery()
1825            >>> Select().select("x").from_(subquery).sql()
1826            'SELECT x FROM (SELECT x FROM tbl)'
1827
1828        Args:
1829            alias (str | Identifier): an optional alias for the subquery
1830            copy (bool): if `False`, modify this expression instance in-place.
1831
1832        Returns:
1833            Alias: the subquery
1834        """
1835        instance = _maybe_copy(self, copy)
1836        return Subquery(
1837            this=instance,
1838            alias=TableAlias(this=to_identifier(alias)) if alias else None,
1839        )
1840
1841    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1842        raise NotImplementedError
1843
1844    @property
1845    def ctes(self):
1846        with_ = self.args.get("with")
1847        if not with_:
1848            return []
1849        return with_.expressions
1850
1851    @property
1852    def selects(self):
1853        raise NotImplementedError("Subqueryable objects must implement `selects`")
1854
1855    @property
1856    def named_selects(self):
1857        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
1858
1859    def with_(
1860        self,
1861        alias,
1862        as_,
1863        recursive=None,
1864        append=True,
1865        dialect=None,
1866        copy=True,
1867        **opts,
1868    ):
1869        """
1870        Append to or set the common table expressions.
1871
1872        Example:
1873            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
1874            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
1875
1876        Args:
1877            alias (str | Expression): the SQL code string to parse as the table name.
1878                If an `Expression` instance is passed, this is used as-is.
1879            as_ (str | Expression): the SQL code string to parse as the table expression.
1880                If an `Expression` instance is passed, it will be used as-is.
1881            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
1882            append (bool): if `True`, add to any existing expressions.
1883                Otherwise, this resets the expressions.
1884            dialect (str): the dialect used to parse the input expression.
1885            copy (bool): if `False`, modify this expression instance in-place.
1886            opts (kwargs): other options to use to parse the input expressions.
1887
1888        Returns:
1889            Select: the modified expression.
1890        """
1891        alias_expression = maybe_parse(
1892            alias,
1893            dialect=dialect,
1894            into=TableAlias,
1895            **opts,
1896        )
1897        as_expression = maybe_parse(
1898            as_,
1899            dialect=dialect,
1900            **opts,
1901        )
1902        cte = CTE(
1903            this=as_expression,
1904            alias=alias_expression,
1905        )
1906        return _apply_child_list_builder(
1907            cte,
1908            instance=self,
1909            arg="with",
1910            append=append,
1911            copy=copy,
1912            into=With,
1913            properties={"recursive": recursive or False},
1914        )
def subquery(self, alias=None, copy=True) -> sqlglot.expressions.Subquery:
1819    def subquery(self, alias=None, copy=True) -> Subquery:
1820        """
1821        Convert this expression to an aliased expression that can be used as a Subquery.
1822
1823        Example:
1824            >>> subquery = Select().select("x").from_("tbl").subquery()
1825            >>> Select().select("x").from_(subquery).sql()
1826            'SELECT x FROM (SELECT x FROM tbl)'
1827
1828        Args:
1829            alias (str | Identifier): an optional alias for the subquery
1830            copy (bool): if `False`, modify this expression instance in-place.
1831
1832        Returns:
1833            Alias: the subquery
1834        """
1835        instance = _maybe_copy(self, copy)
1836        return Subquery(
1837            this=instance,
1838            alias=TableAlias(this=to_identifier(alias)) if alias else None,
1839        )

Convert this expression to an aliased expression that can be used as a Subquery.

Example:
>>> subquery = Select().select("x").from_("tbl").subquery()
>>> Select().select("x").from_(subquery).sql()
'SELECT x FROM (SELECT x FROM tbl)'
Arguments:
  • alias (str | Identifier): an optional alias for the subquery
  • copy (bool): if False, modify this expression instance in-place.
Returns:

Alias: the subquery

def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
1841    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1842        raise NotImplementedError
def with_( self, alias, as_, recursive=None, append=True, dialect=None, copy=True, **opts):
1859    def with_(
1860        self,
1861        alias,
1862        as_,
1863        recursive=None,
1864        append=True,
1865        dialect=None,
1866        copy=True,
1867        **opts,
1868    ):
1869        """
1870        Append to or set the common table expressions.
1871
1872        Example:
1873            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
1874            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
1875
1876        Args:
1877            alias (str | Expression): the SQL code string to parse as the table name.
1878                If an `Expression` instance is passed, this is used as-is.
1879            as_ (str | Expression): the SQL code string to parse as the table expression.
1880                If an `Expression` instance is passed, it will be used as-is.
1881            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
1882            append (bool): if `True`, add to any existing expressions.
1883                Otherwise, this resets the expressions.
1884            dialect (str): the dialect used to parse the input expression.
1885            copy (bool): if `False`, modify this expression instance in-place.
1886            opts (kwargs): other options to use to parse the input expressions.
1887
1888        Returns:
1889            Select: the modified expression.
1890        """
1891        alias_expression = maybe_parse(
1892            alias,
1893            dialect=dialect,
1894            into=TableAlias,
1895            **opts,
1896        )
1897        as_expression = maybe_parse(
1898            as_,
1899            dialect=dialect,
1900            **opts,
1901        )
1902        cte = CTE(
1903            this=as_expression,
1904            alias=alias_expression,
1905        )
1906        return _apply_child_list_builder(
1907            cte,
1908            instance=self,
1909            arg="with",
1910            append=append,
1911            copy=copy,
1912            into=With,
1913            properties={"recursive": recursive or False},
1914        )

Append to or set the common table expressions.

Example:
>>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
Arguments:
  • alias (str | Expression): the SQL code string to parse as the table name. If an Expression instance is passed, this is used as-is.
  • as_ (str | Expression): the SQL code string to parse as the table expression. If an Expression instance is passed, it will be used as-is.
  • recursive (bool): set the RECURSIVE part of the expression. Defaults to False.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

class Table(Expression):
1938class Table(Expression):
1939    arg_types = {
1940        "this": True,
1941        "alias": False,
1942        "db": False,
1943        "catalog": False,
1944        "laterals": False,
1945        "joins": False,
1946        "pivots": False,
1947        "hints": False,
1948        "system_time": False,
1949    }
1950
1951    @property
1952    def db(self) -> str:
1953        return self.text("db")
1954
1955    @property
1956    def catalog(self) -> str:
1957        return self.text("catalog")
class SystemTime(Expression):
1961class SystemTime(Expression):
1962    arg_types = {
1963        "this": False,
1964        "expression": False,
1965        "kind": True,
1966    }
class Union(Subqueryable):
1969class Union(Subqueryable):
1970    arg_types = {
1971        "with": False,
1972        "this": True,
1973        "expression": True,
1974        "distinct": False,
1975        **QUERY_MODIFIERS,
1976    }
1977
1978    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1979        """
1980        Set the LIMIT expression.
1981
1982        Example:
1983            >>> select("1").union(select("1")).limit(1).sql()
1984            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
1985
1986        Args:
1987            expression (str | int | Expression): the SQL code string to parse.
1988                This can also be an integer.
1989                If a `Limit` instance is passed, this is used as-is.
1990                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
1991            dialect (str): the dialect used to parse the input expression.
1992            copy (bool): if `False`, modify this expression instance in-place.
1993            opts (kwargs): other options to use to parse the input expressions.
1994
1995        Returns:
1996            Select: The limited subqueryable.
1997        """
1998        return (
1999            select("*")
2000            .from_(self.subquery(alias="_l_0", copy=copy))
2001            .limit(expression, dialect=dialect, copy=False, **opts)
2002        )
2003
2004    def select(
2005        self,
2006        *expressions: ExpOrStr,
2007        append: bool = True,
2008        dialect: DialectType = None,
2009        copy: bool = True,
2010        **opts,
2011    ) -> Union:
2012        """Append to or set the SELECT of the union recursively.
2013
2014        Example:
2015            >>> from sqlglot import parse_one
2016            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2017            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2018
2019        Args:
2020            *expressions: the SQL code strings to parse.
2021                If an `Expression` instance is passed, it will be used as-is.
2022            append: if `True`, add to any existing expressions.
2023                Otherwise, this resets the expressions.
2024            dialect: the dialect used to parse the input expressions.
2025            copy: if `False`, modify this expression instance in-place.
2026            opts: other options to use to parse the input expressions.
2027
2028        Returns:
2029            Union: the modified expression.
2030        """
2031        this = self.copy() if copy else self
2032        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2033        this.expression.unnest().select(
2034            *expressions, append=append, dialect=dialect, copy=False, **opts
2035        )
2036        return this
2037
2038    @property
2039    def named_selects(self):
2040        return self.this.unnest().named_selects
2041
2042    @property
2043    def is_star(self) -> bool:
2044        return self.this.is_star or self.expression.is_star
2045
2046    @property
2047    def selects(self):
2048        return self.this.unnest().selects
2049
2050    @property
2051    def left(self):
2052        return self.this
2053
2054    @property
2055    def right(self):
2056        return self.expression
def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
1978    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1979        """
1980        Set the LIMIT expression.
1981
1982        Example:
1983            >>> select("1").union(select("1")).limit(1).sql()
1984            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
1985
1986        Args:
1987            expression (str | int | Expression): the SQL code string to parse.
1988                This can also be an integer.
1989                If a `Limit` instance is passed, this is used as-is.
1990                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
1991            dialect (str): the dialect used to parse the input expression.
1992            copy (bool): if `False`, modify this expression instance in-place.
1993            opts (kwargs): other options to use to parse the input expressions.
1994
1995        Returns:
1996            Select: The limited subqueryable.
1997        """
1998        return (
1999            select("*")
2000            .from_(self.subquery(alias="_l_0", copy=copy))
2001            .limit(expression, dialect=dialect, copy=False, **opts)
2002        )

Set the LIMIT expression.

Example:
>>> select("1").union(select("1")).limit(1).sql()
'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
Arguments:
  • expression (str | int | Expression): the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: The limited subqueryable.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Union:
2004    def select(
2005        self,
2006        *expressions: ExpOrStr,
2007        append: bool = True,
2008        dialect: DialectType = None,
2009        copy: bool = True,
2010        **opts,
2011    ) -> Union:
2012        """Append to or set the SELECT of the union recursively.
2013
2014        Example:
2015            >>> from sqlglot import parse_one
2016            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2017            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2018
2019        Args:
2020            *expressions: the SQL code strings to parse.
2021                If an `Expression` instance is passed, it will be used as-is.
2022            append: if `True`, add to any existing expressions.
2023                Otherwise, this resets the expressions.
2024            dialect: the dialect used to parse the input expressions.
2025            copy: if `False`, modify this expression instance in-place.
2026            opts: other options to use to parse the input expressions.
2027
2028        Returns:
2029            Union: the modified expression.
2030        """
2031        this = self.copy() if copy else self
2032        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2033        this.expression.unnest().select(
2034            *expressions, append=append, dialect=dialect, copy=False, **opts
2035        )
2036        return this

Append to or set the SELECT of the union recursively.

Example:
>>> from sqlglot import parse_one
>>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Union: the modified expression.

is_star: bool

Checks whether an expression is a star.

class Except(Union):
2059class Except(Union):
2060    pass
class Intersect(Union):
2063class Intersect(Union):
2064    pass
class Unnest(UDTF):
2067class Unnest(UDTF):
2068    arg_types = {
2069        "expressions": True,
2070        "ordinality": False,
2071        "alias": False,
2072        "offset": False,
2073    }
class Update(Expression):
2076class Update(Expression):
2077    arg_types = {
2078        "with": False,
2079        "this": False,
2080        "expressions": True,
2081        "from": False,
2082        "where": False,
2083        "returning": False,
2084    }
class Values(UDTF):
2087class Values(UDTF):
2088    arg_types = {
2089        "expressions": True,
2090        "ordinality": False,
2091        "alias": False,
2092    }
class Var(Expression):
2095class Var(Expression):
2096    pass
class Schema(Expression):
2099class Schema(Expression):
2100    arg_types = {"this": False, "expressions": False}
class Lock(Expression):
2105class Lock(Expression):
2106    arg_types = {"update": True}
class Select(Subqueryable):
2109class Select(Subqueryable):
2110    arg_types = {
2111        "with": False,
2112        "kind": False,
2113        "expressions": False,
2114        "hint": False,
2115        "distinct": False,
2116        "into": False,
2117        "from": False,
2118        **QUERY_MODIFIERS,
2119    }
2120
2121    def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2122        """
2123        Set the FROM expression.
2124
2125        Example:
2126            >>> Select().from_("tbl").select("x").sql()
2127            'SELECT x FROM tbl'
2128
2129        Args:
2130            *expressions (str | Expression): the SQL code strings to parse.
2131                If a `From` instance is passed, this is used as-is.
2132                If another `Expression` instance is passed, it will be wrapped in a `From`.
2133            append (bool): if `True`, add to any existing expressions.
2134                Otherwise, this flattens all the `From` expression into a single expression.
2135            dialect (str): the dialect used to parse the input expression.
2136            copy (bool): if `False`, modify this expression instance in-place.
2137            opts (kwargs): other options to use to parse the input expressions.
2138
2139        Returns:
2140            Select: the modified expression.
2141        """
2142        return _apply_child_list_builder(
2143            *expressions,
2144            instance=self,
2145            arg="from",
2146            append=append,
2147            copy=copy,
2148            prefix="FROM",
2149            into=From,
2150            dialect=dialect,
2151            **opts,
2152        )
2153
2154    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2155        """
2156        Set the GROUP BY expression.
2157
2158        Example:
2159            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2160            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2161
2162        Args:
2163            *expressions (str | Expression): the SQL code strings to parse.
2164                If a `Group` instance is passed, this is used as-is.
2165                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2166                If nothing is passed in then a group by is not applied to the expression
2167            append (bool): if `True`, add to any existing expressions.
2168                Otherwise, this flattens all the `Group` expression into a single expression.
2169            dialect (str): the dialect used to parse the input expression.
2170            copy (bool): if `False`, modify this expression instance in-place.
2171            opts (kwargs): other options to use to parse the input expressions.
2172
2173        Returns:
2174            Select: the modified expression.
2175        """
2176        if not expressions:
2177            return self if not copy else self.copy()
2178        return _apply_child_list_builder(
2179            *expressions,
2180            instance=self,
2181            arg="group",
2182            append=append,
2183            copy=copy,
2184            prefix="GROUP BY",
2185            into=Group,
2186            dialect=dialect,
2187            **opts,
2188        )
2189
2190    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2191        """
2192        Set the ORDER BY expression.
2193
2194        Example:
2195            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2196            'SELECT x FROM tbl ORDER BY x DESC'
2197
2198        Args:
2199            *expressions (str | Expression): the SQL code strings to parse.
2200                If a `Group` instance is passed, this is used as-is.
2201                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2202            append (bool): if `True`, add to any existing expressions.
2203                Otherwise, this flattens all the `Order` expression into a single expression.
2204            dialect (str): the dialect used to parse the input expression.
2205            copy (bool): if `False`, modify this expression instance in-place.
2206            opts (kwargs): other options to use to parse the input expressions.
2207
2208        Returns:
2209            Select: the modified expression.
2210        """
2211        return _apply_child_list_builder(
2212            *expressions,
2213            instance=self,
2214            arg="order",
2215            append=append,
2216            copy=copy,
2217            prefix="ORDER BY",
2218            into=Order,
2219            dialect=dialect,
2220            **opts,
2221        )
2222
2223    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2224        """
2225        Set the SORT BY expression.
2226
2227        Example:
2228            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
2229            'SELECT x FROM tbl SORT BY x DESC'
2230
2231        Args:
2232            *expressions (str | Expression): the SQL code strings to parse.
2233                If a `Group` instance is passed, this is used as-is.
2234                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2235            append (bool): if `True`, add to any existing expressions.
2236                Otherwise, this flattens all the `Order` expression into a single expression.
2237            dialect (str): the dialect used to parse the input expression.
2238            copy (bool): if `False`, modify this expression instance in-place.
2239            opts (kwargs): other options to use to parse the input expressions.
2240
2241        Returns:
2242            Select: the modified expression.
2243        """
2244        return _apply_child_list_builder(
2245            *expressions,
2246            instance=self,
2247            arg="sort",
2248            append=append,
2249            copy=copy,
2250            prefix="SORT BY",
2251            into=Sort,
2252            dialect=dialect,
2253            **opts,
2254        )
2255
2256    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2257        """
2258        Set the CLUSTER BY expression.
2259
2260        Example:
2261            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
2262            'SELECT x FROM tbl CLUSTER BY x DESC'
2263
2264        Args:
2265            *expressions (str | Expression): the SQL code strings to parse.
2266                If a `Group` instance is passed, this is used as-is.
2267                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2268            append (bool): if `True`, add to any existing expressions.
2269                Otherwise, this flattens all the `Order` expression into a single expression.
2270            dialect (str): the dialect used to parse the input expression.
2271            copy (bool): if `False`, modify this expression instance in-place.
2272            opts (kwargs): other options to use to parse the input expressions.
2273
2274        Returns:
2275            Select: the modified expression.
2276        """
2277        return _apply_child_list_builder(
2278            *expressions,
2279            instance=self,
2280            arg="cluster",
2281            append=append,
2282            copy=copy,
2283            prefix="CLUSTER BY",
2284            into=Cluster,
2285            dialect=dialect,
2286            **opts,
2287        )
2288
2289    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2290        """
2291        Set the LIMIT expression.
2292
2293        Example:
2294            >>> Select().from_("tbl").select("x").limit(10).sql()
2295            'SELECT x FROM tbl LIMIT 10'
2296
2297        Args:
2298            expression (str | int | Expression): the SQL code string to parse.
2299                This can also be an integer.
2300                If a `Limit` instance is passed, this is used as-is.
2301                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2302            dialect (str): the dialect used to parse the input expression.
2303            copy (bool): if `False`, modify this expression instance in-place.
2304            opts (kwargs): other options to use to parse the input expressions.
2305
2306        Returns:
2307            Select: the modified expression.
2308        """
2309        return _apply_builder(
2310            expression=expression,
2311            instance=self,
2312            arg="limit",
2313            into=Limit,
2314            prefix="LIMIT",
2315            dialect=dialect,
2316            copy=copy,
2317            **opts,
2318        )
2319
2320    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2321        """
2322        Set the OFFSET expression.
2323
2324        Example:
2325            >>> Select().from_("tbl").select("x").offset(10).sql()
2326            'SELECT x FROM tbl OFFSET 10'
2327
2328        Args:
2329            expression (str | int | Expression): the SQL code string to parse.
2330                This can also be an integer.
2331                If a `Offset` instance is passed, this is used as-is.
2332                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2333            dialect (str): the dialect used to parse the input expression.
2334            copy (bool): if `False`, modify this expression instance in-place.
2335            opts (kwargs): other options to use to parse the input expressions.
2336
2337        Returns:
2338            Select: the modified expression.
2339        """
2340        return _apply_builder(
2341            expression=expression,
2342            instance=self,
2343            arg="offset",
2344            into=Offset,
2345            prefix="OFFSET",
2346            dialect=dialect,
2347            copy=copy,
2348            **opts,
2349        )
2350
2351    def select(
2352        self,
2353        *expressions: ExpOrStr,
2354        append: bool = True,
2355        dialect: DialectType = None,
2356        copy: bool = True,
2357        **opts,
2358    ) -> Select:
2359        """
2360        Append to or set the SELECT expressions.
2361
2362        Example:
2363            >>> Select().select("x", "y").sql()
2364            'SELECT x, y'
2365
2366        Args:
2367            *expressions: the SQL code strings to parse.
2368                If an `Expression` instance is passed, it will be used as-is.
2369            append: if `True`, add to any existing expressions.
2370                Otherwise, this resets the expressions.
2371            dialect: the dialect used to parse the input expressions.
2372            copy: if `False`, modify this expression instance in-place.
2373            opts: other options to use to parse the input expressions.
2374
2375        Returns:
2376            Select: the modified expression.
2377        """
2378        return _apply_list_builder(
2379            *expressions,
2380            instance=self,
2381            arg="expressions",
2382            append=append,
2383            dialect=dialect,
2384            copy=copy,
2385            **opts,
2386        )
2387
2388    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2389        """
2390        Append to or set the LATERAL expressions.
2391
2392        Example:
2393            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2394            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2395
2396        Args:
2397            *expressions (str | Expression): the SQL code strings to parse.
2398                If an `Expression` instance is passed, it will be used as-is.
2399            append (bool): if `True`, add to any existing expressions.
2400                Otherwise, this resets the expressions.
2401            dialect (str): the dialect used to parse the input expressions.
2402            copy (bool): if `False`, modify this expression instance in-place.
2403            opts (kwargs): other options to use to parse the input expressions.
2404
2405        Returns:
2406            Select: the modified expression.
2407        """
2408        return _apply_list_builder(
2409            *expressions,
2410            instance=self,
2411            arg="laterals",
2412            append=append,
2413            into=Lateral,
2414            prefix="LATERAL VIEW",
2415            dialect=dialect,
2416            copy=copy,
2417            **opts,
2418        )
2419
2420    def join(
2421        self,
2422        expression,
2423        on=None,
2424        using=None,
2425        append=True,
2426        join_type=None,
2427        join_alias=None,
2428        dialect=None,
2429        copy=True,
2430        **opts,
2431    ) -> Select:
2432        """
2433        Append to or set the JOIN expressions.
2434
2435        Example:
2436            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2437            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2438
2439            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2440            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2441
2442            Use `join_type` to change the type of join:
2443
2444            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2445            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2446
2447        Args:
2448            expression (str | Expression): the SQL code string to parse.
2449                If an `Expression` instance is passed, it will be used as-is.
2450            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2451                If an `Expression` instance is passed, it will be used as-is.
2452            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2453                If an `Expression` instance is passed, it will be used as-is.
2454            append (bool): if `True`, add to any existing expressions.
2455                Otherwise, this resets the expressions.
2456            join_type (str): If set, alter the parsed join type
2457            dialect (str): the dialect used to parse the input expressions.
2458            copy (bool): if `False`, modify this expression instance in-place.
2459            opts (kwargs): other options to use to parse the input expressions.
2460
2461        Returns:
2462            Select: the modified expression.
2463        """
2464        parse_args = {"dialect": dialect, **opts}
2465
2466        try:
2467            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2468        except ParseError:
2469            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2470
2471        join = expression if isinstance(expression, Join) else Join(this=expression)
2472
2473        if isinstance(join.this, Select):
2474            join.this.replace(join.this.subquery())
2475
2476        if join_type:
2477            natural: t.Optional[Token]
2478            side: t.Optional[Token]
2479            kind: t.Optional[Token]
2480
2481            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2482
2483            if natural:
2484                join.set("natural", True)
2485            if side:
2486                join.set("side", side.text)
2487            if kind:
2488                join.set("kind", kind.text)
2489
2490        if on:
2491            on = and_(*ensure_collection(on), dialect=dialect, **opts)
2492            join.set("on", on)
2493
2494        if using:
2495            join = _apply_list_builder(
2496                *ensure_collection(using),
2497                instance=join,
2498                arg="using",
2499                append=append,
2500                copy=copy,
2501                **opts,
2502            )
2503
2504        if join_alias:
2505            join.set("this", alias_(join.this, join_alias, table=True))
2506        return _apply_list_builder(
2507            join,
2508            instance=self,
2509            arg="joins",
2510            append=append,
2511            copy=copy,
2512            **opts,
2513        )
2514
2515    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2516        """
2517        Append to or set the WHERE expressions.
2518
2519        Example:
2520            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2521            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2522
2523        Args:
2524            *expressions (str | Expression): the SQL code strings to parse.
2525                If an `Expression` instance is passed, it will be used as-is.
2526                Multiple expressions are combined with an AND operator.
2527            append (bool): if `True`, AND the new expressions to any existing expression.
2528                Otherwise, this resets the expression.
2529            dialect (str): the dialect used to parse the input expressions.
2530            copy (bool): if `False`, modify this expression instance in-place.
2531            opts (kwargs): other options to use to parse the input expressions.
2532
2533        Returns:
2534            Select: the modified expression.
2535        """
2536        return _apply_conjunction_builder(
2537            *expressions,
2538            instance=self,
2539            arg="where",
2540            append=append,
2541            into=Where,
2542            dialect=dialect,
2543            copy=copy,
2544            **opts,
2545        )
2546
2547    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2548        """
2549        Append to or set the HAVING expressions.
2550
2551        Example:
2552            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2553            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2554
2555        Args:
2556            *expressions (str | Expression): the SQL code strings to parse.
2557                If an `Expression` instance is passed, it will be used as-is.
2558                Multiple expressions are combined with an AND operator.
2559            append (bool): if `True`, AND the new expressions to any existing expression.
2560                Otherwise, this resets the expression.
2561            dialect (str): the dialect used to parse the input expressions.
2562            copy (bool): if `False`, modify this expression instance in-place.
2563            opts (kwargs): other options to use to parse the input expressions.
2564
2565        Returns:
2566            Select: the modified expression.
2567        """
2568        return _apply_conjunction_builder(
2569            *expressions,
2570            instance=self,
2571            arg="having",
2572            append=append,
2573            into=Having,
2574            dialect=dialect,
2575            copy=copy,
2576            **opts,
2577        )
2578
2579    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2580        return _apply_list_builder(
2581            *expressions,
2582            instance=self,
2583            arg="windows",
2584            append=append,
2585            into=Window,
2586            dialect=dialect,
2587            copy=copy,
2588            **opts,
2589        )
2590
2591    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2592        return _apply_conjunction_builder(
2593            *expressions,
2594            instance=self,
2595            arg="qualify",
2596            append=append,
2597            into=Qualify,
2598            dialect=dialect,
2599            copy=copy,
2600            **opts,
2601        )
2602
2603    def distinct(self, distinct=True, copy=True) -> Select:
2604        """
2605        Set the OFFSET expression.
2606
2607        Example:
2608            >>> Select().from_("tbl").select("x").distinct().sql()
2609            'SELECT DISTINCT x FROM tbl'
2610
2611        Args:
2612            distinct (bool): whether the Select should be distinct
2613            copy (bool): if `False`, modify this expression instance in-place.
2614
2615        Returns:
2616            Select: the modified expression.
2617        """
2618        instance = _maybe_copy(self, copy)
2619        instance.set("distinct", Distinct() if distinct else None)
2620        return instance
2621
2622    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2623        """
2624        Convert this expression to a CREATE TABLE AS statement.
2625
2626        Example:
2627            >>> Select().select("*").from_("tbl").ctas("x").sql()
2628            'CREATE TABLE x AS SELECT * FROM tbl'
2629
2630        Args:
2631            table (str | Expression): the SQL code string to parse as the table name.
2632                If another `Expression` instance is passed, it will be used as-is.
2633            properties (dict): an optional mapping of table properties
2634            dialect (str): the dialect used to parse the input table.
2635            copy (bool): if `False`, modify this expression instance in-place.
2636            opts (kwargs): other options to use to parse the input table.
2637
2638        Returns:
2639            Create: the CREATE TABLE AS expression
2640        """
2641        instance = _maybe_copy(self, copy)
2642        table_expression = maybe_parse(
2643            table,
2644            into=Table,
2645            dialect=dialect,
2646            **opts,
2647        )
2648        properties_expression = None
2649        if properties:
2650            properties_expression = Properties.from_dict(properties)
2651
2652        return Create(
2653            this=table_expression,
2654            kind="table",
2655            expression=instance,
2656            properties=properties_expression,
2657        )
2658
2659    def lock(self, update: bool = True, copy: bool = True) -> Select:
2660        """
2661        Set the locking read mode for this expression.
2662
2663        Examples:
2664            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2665            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2666
2667            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2668            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2669
2670        Args:
2671            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2672            copy: if `False`, modify this expression instance in-place.
2673
2674        Returns:
2675            The modified expression.
2676        """
2677
2678        inst = _maybe_copy(self, copy)
2679        inst.set("lock", Lock(update=update))
2680
2681        return inst
2682
2683    @property
2684    def named_selects(self) -> t.List[str]:
2685        return [e.output_name for e in self.expressions if e.alias_or_name]
2686
2687    @property
2688    def is_star(self) -> bool:
2689        return any(expression.is_star for expression in self.expressions)
2690
2691    @property
2692    def selects(self) -> t.List[Expression]:
2693        return self.expressions
def from_( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2121    def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2122        """
2123        Set the FROM expression.
2124
2125        Example:
2126            >>> Select().from_("tbl").select("x").sql()
2127            'SELECT x FROM tbl'
2128
2129        Args:
2130            *expressions (str | Expression): the SQL code strings to parse.
2131                If a `From` instance is passed, this is used as-is.
2132                If another `Expression` instance is passed, it will be wrapped in a `From`.
2133            append (bool): if `True`, add to any existing expressions.
2134                Otherwise, this flattens all the `From` expression into a single expression.
2135            dialect (str): the dialect used to parse the input expression.
2136            copy (bool): if `False`, modify this expression instance in-place.
2137            opts (kwargs): other options to use to parse the input expressions.
2138
2139        Returns:
2140            Select: the modified expression.
2141        """
2142        return _apply_child_list_builder(
2143            *expressions,
2144            instance=self,
2145            arg="from",
2146            append=append,
2147            copy=copy,
2148            prefix="FROM",
2149            into=From,
2150            dialect=dialect,
2151            **opts,
2152        )

Set the FROM expression.

Example:
>>> Select().from_("tbl").select("x").sql()
'SELECT x FROM tbl'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a From instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a From.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the From expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def group_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2154    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2155        """
2156        Set the GROUP BY expression.
2157
2158        Example:
2159            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2160            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2161
2162        Args:
2163            *expressions (str | Expression): the SQL code strings to parse.
2164                If a `Group` instance is passed, this is used as-is.
2165                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2166                If nothing is passed in then a group by is not applied to the expression
2167            append (bool): if `True`, add to any existing expressions.
2168                Otherwise, this flattens all the `Group` expression into a single expression.
2169            dialect (str): the dialect used to parse the input expression.
2170            copy (bool): if `False`, modify this expression instance in-place.
2171            opts (kwargs): other options to use to parse the input expressions.
2172
2173        Returns:
2174            Select: the modified expression.
2175        """
2176        if not expressions:
2177            return self if not copy else self.copy()
2178        return _apply_child_list_builder(
2179            *expressions,
2180            instance=self,
2181            arg="group",
2182            append=append,
2183            copy=copy,
2184            prefix="GROUP BY",
2185            into=Group,
2186            dialect=dialect,
2187            **opts,
2188        )

Set the GROUP BY expression.

Example:
>>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
'SELECT x, COUNT(1) FROM tbl GROUP BY x'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Group. If nothing is passed in then a group by is not applied to the expression
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Group expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def order_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2190    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2191        """
2192        Set the ORDER BY expression.
2193
2194        Example:
2195            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2196            'SELECT x FROM tbl ORDER BY x DESC'
2197
2198        Args:
2199            *expressions (str | Expression): the SQL code strings to parse.
2200                If a `Group` instance is passed, this is used as-is.
2201                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2202            append (bool): if `True`, add to any existing expressions.
2203                Otherwise, this flattens all the `Order` expression into a single expression.
2204            dialect (str): the dialect used to parse the input expression.
2205            copy (bool): if `False`, modify this expression instance in-place.
2206            opts (kwargs): other options to use to parse the input expressions.
2207
2208        Returns:
2209            Select: the modified expression.
2210        """
2211        return _apply_child_list_builder(
2212            *expressions,
2213            instance=self,
2214            arg="order",
2215            append=append,
2216            copy=copy,
2217            prefix="ORDER BY",
2218            into=Order,
2219            dialect=dialect,
2220            **opts,
2221        )

Set the ORDER BY expression.

Example:
>>> Select().from_("tbl").select("x").order_by("x DESC").sql()
'SELECT x FROM tbl ORDER BY x DESC'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Order.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def sort_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2223    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2224        """
2225        Set the SORT BY expression.
2226
2227        Example:
2228            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
2229            'SELECT x FROM tbl SORT BY x DESC'
2230
2231        Args:
2232            *expressions (str | Expression): the SQL code strings to parse.
2233                If a `Group` instance is passed, this is used as-is.
2234                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2235            append (bool): if `True`, add to any existing expressions.
2236                Otherwise, this flattens all the `Order` expression into a single expression.
2237            dialect (str): the dialect used to parse the input expression.
2238            copy (bool): if `False`, modify this expression instance in-place.
2239            opts (kwargs): other options to use to parse the input expressions.
2240
2241        Returns:
2242            Select: the modified expression.
2243        """
2244        return _apply_child_list_builder(
2245            *expressions,
2246            instance=self,
2247            arg="sort",
2248            append=append,
2249            copy=copy,
2250            prefix="SORT BY",
2251            into=Sort,
2252            dialect=dialect,
2253            **opts,
2254        )

Set the SORT BY expression.

Example:
>>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
'SELECT x FROM tbl SORT BY x DESC'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a SORT.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def cluster_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2256    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2257        """
2258        Set the CLUSTER BY expression.
2259
2260        Example:
2261            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
2262            'SELECT x FROM tbl CLUSTER BY x DESC'
2263
2264        Args:
2265            *expressions (str | Expression): the SQL code strings to parse.
2266                If a `Group` instance is passed, this is used as-is.
2267                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2268            append (bool): if `True`, add to any existing expressions.
2269                Otherwise, this flattens all the `Order` expression into a single expression.
2270            dialect (str): the dialect used to parse the input expression.
2271            copy (bool): if `False`, modify this expression instance in-place.
2272            opts (kwargs): other options to use to parse the input expressions.
2273
2274        Returns:
2275            Select: the modified expression.
2276        """
2277        return _apply_child_list_builder(
2278            *expressions,
2279            instance=self,
2280            arg="cluster",
2281            append=append,
2282            copy=copy,
2283            prefix="CLUSTER BY",
2284            into=Cluster,
2285            dialect=dialect,
2286            **opts,
2287        )

Set the CLUSTER BY expression.

Example:
>>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
'SELECT x FROM tbl CLUSTER BY x DESC'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Cluster.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2289    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2290        """
2291        Set the LIMIT expression.
2292
2293        Example:
2294            >>> Select().from_("tbl").select("x").limit(10).sql()
2295            'SELECT x FROM tbl LIMIT 10'
2296
2297        Args:
2298            expression (str | int | Expression): the SQL code string to parse.
2299                This can also be an integer.
2300                If a `Limit` instance is passed, this is used as-is.
2301                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2302            dialect (str): the dialect used to parse the input expression.
2303            copy (bool): if `False`, modify this expression instance in-place.
2304            opts (kwargs): other options to use to parse the input expressions.
2305
2306        Returns:
2307            Select: the modified expression.
2308        """
2309        return _apply_builder(
2310            expression=expression,
2311            instance=self,
2312            arg="limit",
2313            into=Limit,
2314            prefix="LIMIT",
2315            dialect=dialect,
2316            copy=copy,
2317            **opts,
2318        )

Set the LIMIT expression.

Example:
>>> Select().from_("tbl").select("x").limit(10).sql()
'SELECT x FROM tbl LIMIT 10'
Arguments:
  • expression (str | int | Expression): the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def offset( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2320    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2321        """
2322        Set the OFFSET expression.
2323
2324        Example:
2325            >>> Select().from_("tbl").select("x").offset(10).sql()
2326            'SELECT x FROM tbl OFFSET 10'
2327
2328        Args:
2329            expression (str | int | Expression): the SQL code string to parse.
2330                This can also be an integer.
2331                If a `Offset` instance is passed, this is used as-is.
2332                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2333            dialect (str): the dialect used to parse the input expression.
2334            copy (bool): if `False`, modify this expression instance in-place.
2335            opts (kwargs): other options to use to parse the input expressions.
2336
2337        Returns:
2338            Select: the modified expression.
2339        """
2340        return _apply_builder(
2341            expression=expression,
2342            instance=self,
2343            arg="offset",
2344            into=Offset,
2345            prefix="OFFSET",
2346            dialect=dialect,
2347            copy=copy,
2348            **opts,
2349        )

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").offset(10).sql()
'SELECT x FROM tbl OFFSET 10'
Arguments:
  • expression (str | int | Expression): the SQL code string to parse. This can also be an integer. If a Offset instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Offset.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2351    def select(
2352        self,
2353        *expressions: ExpOrStr,
2354        append: bool = True,
2355        dialect: DialectType = None,
2356        copy: bool = True,
2357        **opts,
2358    ) -> Select:
2359        """
2360        Append to or set the SELECT expressions.
2361
2362        Example:
2363            >>> Select().select("x", "y").sql()
2364            'SELECT x, y'
2365
2366        Args:
2367            *expressions: the SQL code strings to parse.
2368                If an `Expression` instance is passed, it will be used as-is.
2369            append: if `True`, add to any existing expressions.
2370                Otherwise, this resets the expressions.
2371            dialect: the dialect used to parse the input expressions.
2372            copy: if `False`, modify this expression instance in-place.
2373            opts: other options to use to parse the input expressions.
2374
2375        Returns:
2376            Select: the modified expression.
2377        """
2378        return _apply_list_builder(
2379            *expressions,
2380            instance=self,
2381            arg="expressions",
2382            append=append,
2383            dialect=dialect,
2384            copy=copy,
2385            **opts,
2386        )

Append to or set the SELECT expressions.

Example:
>>> Select().select("x", "y").sql()
'SELECT x, y'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def lateral( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2388    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2389        """
2390        Append to or set the LATERAL expressions.
2391
2392        Example:
2393            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2394            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2395
2396        Args:
2397            *expressions (str | Expression): the SQL code strings to parse.
2398                If an `Expression` instance is passed, it will be used as-is.
2399            append (bool): if `True`, add to any existing expressions.
2400                Otherwise, this resets the expressions.
2401            dialect (str): the dialect used to parse the input expressions.
2402            copy (bool): if `False`, modify this expression instance in-place.
2403            opts (kwargs): other options to use to parse the input expressions.
2404
2405        Returns:
2406            Select: the modified expression.
2407        """
2408        return _apply_list_builder(
2409            *expressions,
2410            instance=self,
2411            arg="laterals",
2412            append=append,
2413            into=Lateral,
2414            prefix="LATERAL VIEW",
2415            dialect=dialect,
2416            copy=copy,
2417            **opts,
2418        )

Append to or set the LATERAL expressions.

Example:
>>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def join( self, expression, on=None, using=None, append=True, join_type=None, join_alias=None, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2420    def join(
2421        self,
2422        expression,
2423        on=None,
2424        using=None,
2425        append=True,
2426        join_type=None,
2427        join_alias=None,
2428        dialect=None,
2429        copy=True,
2430        **opts,
2431    ) -> Select:
2432        """
2433        Append to or set the JOIN expressions.
2434
2435        Example:
2436            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2437            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2438
2439            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2440            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2441
2442            Use `join_type` to change the type of join:
2443
2444            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2445            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2446
2447        Args:
2448            expression (str | Expression): the SQL code string to parse.
2449                If an `Expression` instance is passed, it will be used as-is.
2450            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2451                If an `Expression` instance is passed, it will be used as-is.
2452            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2453                If an `Expression` instance is passed, it will be used as-is.
2454            append (bool): if `True`, add to any existing expressions.
2455                Otherwise, this resets the expressions.
2456            join_type (str): If set, alter the parsed join type
2457            dialect (str): the dialect used to parse the input expressions.
2458            copy (bool): if `False`, modify this expression instance in-place.
2459            opts (kwargs): other options to use to parse the input expressions.
2460
2461        Returns:
2462            Select: the modified expression.
2463        """
2464        parse_args = {"dialect": dialect, **opts}
2465
2466        try:
2467            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2468        except ParseError:
2469            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2470
2471        join = expression if isinstance(expression, Join) else Join(this=expression)
2472
2473        if isinstance(join.this, Select):
2474            join.this.replace(join.this.subquery())
2475
2476        if join_type:
2477            natural: t.Optional[Token]
2478            side: t.Optional[Token]
2479            kind: t.Optional[Token]
2480
2481            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2482
2483            if natural:
2484                join.set("natural", True)
2485            if side:
2486                join.set("side", side.text)
2487            if kind:
2488                join.set("kind", kind.text)
2489
2490        if on:
2491            on = and_(*ensure_collection(on), dialect=dialect, **opts)
2492            join.set("on", on)
2493
2494        if using:
2495            join = _apply_list_builder(
2496                *ensure_collection(using),
2497                instance=join,
2498                arg="using",
2499                append=append,
2500                copy=copy,
2501                **opts,
2502            )
2503
2504        if join_alias:
2505            join.set("this", alias_(join.this, join_alias, table=True))
2506        return _apply_list_builder(
2507            join,
2508            instance=self,
2509            arg="joins",
2510            append=append,
2511            copy=copy,
2512            **opts,
2513        )

Append to or set the JOIN expressions.

Example:
>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
>>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
'SELECT 1 FROM a JOIN b USING (x, y, z)'

Use join_type to change the type of join:

>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
Arguments:
  • expression (str | Expression): the SQL code string to parse. If an Expression instance is passed, it will be used as-is.
  • on (str | Expression): optionally specify the join "on" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • using (str | Expression): optionally specify the join "using" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • join_type (str): If set, alter the parsed join type
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def where( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2515    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2516        """
2517        Append to or set the WHERE expressions.
2518
2519        Example:
2520            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2521            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2522
2523        Args:
2524            *expressions (str | Expression): the SQL code strings to parse.
2525                If an `Expression` instance is passed, it will be used as-is.
2526                Multiple expressions are combined with an AND operator.
2527            append (bool): if `True`, AND the new expressions to any existing expression.
2528                Otherwise, this resets the expression.
2529            dialect (str): the dialect used to parse the input expressions.
2530            copy (bool): if `False`, modify this expression instance in-place.
2531            opts (kwargs): other options to use to parse the input expressions.
2532
2533        Returns:
2534            Select: the modified expression.
2535        """
2536        return _apply_conjunction_builder(
2537            *expressions,
2538            instance=self,
2539            arg="where",
2540            append=append,
2541            into=Where,
2542            dialect=dialect,
2543            copy=copy,
2544            **opts,
2545        )

Append to or set the WHERE expressions.

Example:
>>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
"SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def having( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2547    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2548        """
2549        Append to or set the HAVING expressions.
2550
2551        Example:
2552            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2553            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2554
2555        Args:
2556            *expressions (str | Expression): the SQL code strings to parse.
2557                If an `Expression` instance is passed, it will be used as-is.
2558                Multiple expressions are combined with an AND operator.
2559            append (bool): if `True`, AND the new expressions to any existing expression.
2560                Otherwise, this resets the expression.
2561            dialect (str): the dialect used to parse the input expressions.
2562            copy (bool): if `False`, modify this expression instance in-place.
2563            opts (kwargs): other options to use to parse the input expressions.
2564
2565        Returns:
2566            Select: the modified expression.
2567        """
2568        return _apply_conjunction_builder(
2569            *expressions,
2570            instance=self,
2571            arg="having",
2572            append=append,
2573            into=Having,
2574            dialect=dialect,
2575            copy=copy,
2576            **opts,
2577        )

Append to or set the HAVING expressions.

Example:
>>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def window( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2579    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2580        return _apply_list_builder(
2581            *expressions,
2582            instance=self,
2583            arg="windows",
2584            append=append,
2585            into=Window,
2586            dialect=dialect,
2587            copy=copy,
2588            **opts,
2589        )
def qualify( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2591    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2592        return _apply_conjunction_builder(
2593            *expressions,
2594            instance=self,
2595            arg="qualify",
2596            append=append,
2597            into=Qualify,
2598            dialect=dialect,
2599            copy=copy,
2600            **opts,
2601        )
def distinct(self, distinct=True, copy=True) -> sqlglot.expressions.Select:
2603    def distinct(self, distinct=True, copy=True) -> Select:
2604        """
2605        Set the OFFSET expression.
2606
2607        Example:
2608            >>> Select().from_("tbl").select("x").distinct().sql()
2609            'SELECT DISTINCT x FROM tbl'
2610
2611        Args:
2612            distinct (bool): whether the Select should be distinct
2613            copy (bool): if `False`, modify this expression instance in-place.
2614
2615        Returns:
2616            Select: the modified expression.
2617        """
2618        instance = _maybe_copy(self, copy)
2619        instance.set("distinct", Distinct() if distinct else None)
2620        return instance

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").distinct().sql()
'SELECT DISTINCT x FROM tbl'
Arguments:
  • distinct (bool): whether the Select should be distinct
  • copy (bool): if False, modify this expression instance in-place.
Returns:

Select: the modified expression.

def ctas( self, table, properties=None, dialect=None, copy=True, **opts) -> sqlglot.expressions.Create:
2622    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2623        """
2624        Convert this expression to a CREATE TABLE AS statement.
2625
2626        Example:
2627            >>> Select().select("*").from_("tbl").ctas("x").sql()
2628            'CREATE TABLE x AS SELECT * FROM tbl'
2629
2630        Args:
2631            table (str | Expression): the SQL code string to parse as the table name.
2632                If another `Expression` instance is passed, it will be used as-is.
2633            properties (dict): an optional mapping of table properties
2634            dialect (str): the dialect used to parse the input table.
2635            copy (bool): if `False`, modify this expression instance in-place.
2636            opts (kwargs): other options to use to parse the input table.
2637
2638        Returns:
2639            Create: the CREATE TABLE AS expression
2640        """
2641        instance = _maybe_copy(self, copy)
2642        table_expression = maybe_parse(
2643            table,
2644            into=Table,
2645            dialect=dialect,
2646            **opts,
2647        )
2648        properties_expression = None
2649        if properties:
2650            properties_expression = Properties.from_dict(properties)
2651
2652        return Create(
2653            this=table_expression,
2654            kind="table",
2655            expression=instance,
2656            properties=properties_expression,
2657        )

Convert this expression to a CREATE TABLE AS statement.

Example:
>>> Select().select("*").from_("tbl").ctas("x").sql()
'CREATE TABLE x AS SELECT * FROM tbl'
Arguments:
  • table (str | Expression): the SQL code string to parse as the table name. If another Expression instance is passed, it will be used as-is.
  • properties (dict): an optional mapping of table properties
  • dialect (str): the dialect used to parse the input table.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input table.
Returns:

Create: the CREATE TABLE AS expression

def lock( self, update: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
2659    def lock(self, update: bool = True, copy: bool = True) -> Select:
2660        """
2661        Set the locking read mode for this expression.
2662
2663        Examples:
2664            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2665            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2666
2667            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2668            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2669
2670        Args:
2671            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2672            copy: if `False`, modify this expression instance in-place.
2673
2674        Returns:
2675            The modified expression.
2676        """
2677
2678        inst = _maybe_copy(self, copy)
2679        inst.set("lock", Lock(update=update))
2680
2681        return inst

Set the locking read mode for this expression.

Examples:
>>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
>>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
Arguments:
  • update: if True, the locking type will be FOR UPDATE, else it will be FOR SHARE.
  • copy: if False, modify this expression instance in-place.
Returns:

The modified expression.

is_star: bool

Checks whether an expression is a star.

class Subquery(DerivedTable, Unionable):
2696class Subquery(DerivedTable, Unionable):
2697    arg_types = {
2698        "this": True,
2699        "alias": False,
2700        "with": False,
2701        **QUERY_MODIFIERS,
2702    }
2703
2704    def unnest(self):
2705        """
2706        Returns the first non subquery.
2707        """
2708        expression = self
2709        while isinstance(expression, Subquery):
2710            expression = expression.this
2711        return expression
2712
2713    @property
2714    def is_star(self) -> bool:
2715        return self.this.is_star
2716
2717    @property
2718    def output_name(self):
2719        return self.alias
def unnest(self):
2704    def unnest(self):
2705        """
2706        Returns the first non subquery.
2707        """
2708        expression = self
2709        while isinstance(expression, Subquery):
2710            expression = expression.this
2711        return expression

Returns the first non subquery.

is_star: bool

Checks whether an expression is a star.

output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class TableSample(Expression):
2722class TableSample(Expression):
2723    arg_types = {
2724        "this": False,
2725        "method": False,
2726        "bucket_numerator": False,
2727        "bucket_denominator": False,
2728        "bucket_field": False,
2729        "percent": False,
2730        "rows": False,
2731        "size": False,
2732        "seed": False,
2733        "kind": False,
2734    }
class Tag(Expression):
2737class Tag(Expression):
2738    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
2739
2740    arg_types = {
2741        "this": False,
2742        "prefix": False,
2743        "postfix": False,
2744    }

Tags are used for generating arbitrary sql like SELECT x.

class Pivot(Expression):
2747class Pivot(Expression):
2748    arg_types = {
2749        "this": False,
2750        "alias": False,
2751        "expressions": True,
2752        "field": True,
2753        "unpivot": True,
2754        "columns": False,
2755    }
class Window(Expression):
2758class Window(Expression):
2759    arg_types = {
2760        "this": True,
2761        "partition_by": False,
2762        "order": False,
2763        "spec": False,
2764        "alias": False,
2765    }
class WindowSpec(Expression):
2768class WindowSpec(Expression):
2769    arg_types = {
2770        "kind": False,
2771        "start": False,
2772        "start_side": False,
2773        "end": False,
2774        "end_side": False,
2775    }
class Where(Expression):
2778class Where(Expression):
2779    pass
class Star(Expression):
2782class Star(Expression):
2783    arg_types = {"except": False, "replace": False}
2784
2785    @property
2786    def name(self) -> str:
2787        return "*"
2788
2789    @property
2790    def output_name(self):
2791        return self.name
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Parameter(Expression):
2794class Parameter(Expression):
2795    arg_types = {"this": True, "wrapped": False}
class SessionParameter(Expression):
2798class SessionParameter(Expression):
2799    arg_types = {"this": True, "kind": False}
class Placeholder(Expression):
2802class Placeholder(Expression):
2803    arg_types = {"this": False}
class Null(Condition):
2806class Null(Condition):
2807    arg_types: t.Dict[str, t.Any] = {}
2808
2809    @property
2810    def name(self) -> str:
2811        return "NULL"
class Boolean(Condition):
2814class Boolean(Condition):
2815    pass
class DataType(Expression):
2818class DataType(Expression):
2819    arg_types = {
2820        "this": True,
2821        "expressions": False,
2822        "nested": False,
2823        "values": False,
2824        "prefix": False,
2825    }
2826
2827    class Type(AutoName):
2828        CHAR = auto()
2829        NCHAR = auto()
2830        VARCHAR = auto()
2831        NVARCHAR = auto()
2832        TEXT = auto()
2833        MEDIUMTEXT = auto()
2834        LONGTEXT = auto()
2835        MEDIUMBLOB = auto()
2836        LONGBLOB = auto()
2837        BINARY = auto()
2838        VARBINARY = auto()
2839        INT = auto()
2840        UINT = auto()
2841        TINYINT = auto()
2842        UTINYINT = auto()
2843        SMALLINT = auto()
2844        USMALLINT = auto()
2845        BIGINT = auto()
2846        UBIGINT = auto()
2847        FLOAT = auto()
2848        DOUBLE = auto()
2849        DECIMAL = auto()
2850        BIGDECIMAL = auto()
2851        BIT = auto()
2852        BOOLEAN = auto()
2853        JSON = auto()
2854        JSONB = auto()
2855        INTERVAL = auto()
2856        TIME = auto()
2857        TIMESTAMP = auto()
2858        TIMESTAMPTZ = auto()
2859        TIMESTAMPLTZ = auto()
2860        DATE = auto()
2861        DATETIME = auto()
2862        ARRAY = auto()
2863        MAP = auto()
2864        UUID = auto()
2865        GEOGRAPHY = auto()
2866        GEOMETRY = auto()
2867        STRUCT = auto()
2868        NULLABLE = auto()
2869        HLLSKETCH = auto()
2870        HSTORE = auto()
2871        SUPER = auto()
2872        SERIAL = auto()
2873        SMALLSERIAL = auto()
2874        BIGSERIAL = auto()
2875        XML = auto()
2876        UNIQUEIDENTIFIER = auto()
2877        MONEY = auto()
2878        SMALLMONEY = auto()
2879        ROWVERSION = auto()
2880        IMAGE = auto()
2881        VARIANT = auto()
2882        OBJECT = auto()
2883        INET = auto()
2884        NULL = auto()
2885        UNKNOWN = auto()  # Sentinel value, useful for type annotation
2886
2887    TEXT_TYPES = {
2888        Type.CHAR,
2889        Type.NCHAR,
2890        Type.VARCHAR,
2891        Type.NVARCHAR,
2892        Type.TEXT,
2893    }
2894
2895    INTEGER_TYPES = {
2896        Type.INT,
2897        Type.TINYINT,
2898        Type.SMALLINT,
2899        Type.BIGINT,
2900    }
2901
2902    FLOAT_TYPES = {
2903        Type.FLOAT,
2904        Type.DOUBLE,
2905    }
2906
2907    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
2908
2909    TEMPORAL_TYPES = {
2910        Type.TIMESTAMP,
2911        Type.TIMESTAMPTZ,
2912        Type.TIMESTAMPLTZ,
2913        Type.DATE,
2914        Type.DATETIME,
2915    }
2916
2917    @classmethod
2918    def build(
2919        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
2920    ) -> DataType:
2921        from sqlglot import parse_one
2922
2923        if isinstance(dtype, str):
2924            if dtype.upper() in cls.Type.__members__:
2925                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
2926            else:
2927                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
2928            if data_type_exp is None:
2929                raise ValueError(f"Unparsable data type value: {dtype}")
2930        elif isinstance(dtype, DataType.Type):
2931            data_type_exp = DataType(this=dtype)
2932        elif isinstance(dtype, DataType):
2933            return dtype
2934        else:
2935            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
2936        return DataType(**{**data_type_exp.args, **kwargs})
2937
2938    def is_type(self, dtype: DataType.Type) -> bool:
2939        return self.this == dtype
@classmethod
def build( cls, dtype: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.DataType:
2917    @classmethod
2918    def build(
2919        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
2920    ) -> DataType:
2921        from sqlglot import parse_one
2922
2923        if isinstance(dtype, str):
2924            if dtype.upper() in cls.Type.__members__:
2925                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
2926            else:
2927                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
2928            if data_type_exp is None:
2929                raise ValueError(f"Unparsable data type value: {dtype}")
2930        elif isinstance(dtype, DataType.Type):
2931            data_type_exp = DataType(this=dtype)
2932        elif isinstance(dtype, DataType):
2933            return dtype
2934        else:
2935            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
2936        return DataType(**{**data_type_exp.args, **kwargs})
def is_type(self, dtype: sqlglot.expressions.DataType.Type) -> bool:
2938    def is_type(self, dtype: DataType.Type) -> bool:
2939        return self.this == dtype
class DataType.Type(sqlglot.helper.AutoName):
2827    class Type(AutoName):
2828        CHAR = auto()
2829        NCHAR = auto()
2830        VARCHAR = auto()
2831        NVARCHAR = auto()
2832        TEXT = auto()
2833        MEDIUMTEXT = auto()
2834        LONGTEXT = auto()
2835        MEDIUMBLOB = auto()
2836        LONGBLOB = auto()
2837        BINARY = auto()
2838        VARBINARY = auto()
2839        INT = auto()
2840        UINT = auto()
2841        TINYINT = auto()
2842        UTINYINT = auto()
2843        SMALLINT = auto()
2844        USMALLINT = auto()
2845        BIGINT = auto()
2846        UBIGINT = auto()
2847        FLOAT = auto()
2848        DOUBLE = auto()
2849        DECIMAL = auto()
2850        BIGDECIMAL = auto()
2851        BIT = auto()
2852        BOOLEAN = auto()
2853        JSON = auto()
2854        JSONB = auto()
2855        INTERVAL = auto()
2856        TIME = auto()
2857        TIMESTAMP = auto()
2858        TIMESTAMPTZ = auto()
2859        TIMESTAMPLTZ = auto()
2860        DATE = auto()
2861        DATETIME = auto()
2862        ARRAY = auto()
2863        MAP = auto()
2864        UUID = auto()
2865        GEOGRAPHY = auto()
2866        GEOMETRY = auto()
2867        STRUCT = auto()
2868        NULLABLE = auto()
2869        HLLSKETCH = auto()
2870        HSTORE = auto()
2871        SUPER = auto()
2872        SERIAL = auto()
2873        SMALLSERIAL = auto()
2874        BIGSERIAL = auto()
2875        XML = auto()
2876        UNIQUEIDENTIFIER = auto()
2877        MONEY = auto()
2878        SMALLMONEY = auto()
2879        ROWVERSION = auto()
2880        IMAGE = auto()
2881        VARIANT = auto()
2882        OBJECT = auto()
2883        INET = auto()
2884        NULL = auto()
2885        UNKNOWN = auto()  # Sentinel value, useful for type annotation

An enumeration.

CHAR = <Type.CHAR: 'CHAR'>
NCHAR = <Type.NCHAR: 'NCHAR'>
VARCHAR = <Type.VARCHAR: 'VARCHAR'>
NVARCHAR = <Type.NVARCHAR: 'NVARCHAR'>
TEXT = <Type.TEXT: 'TEXT'>
MEDIUMTEXT = <Type.MEDIUMTEXT: 'MEDIUMTEXT'>
LONGTEXT = <Type.LONGTEXT: 'LONGTEXT'>
MEDIUMBLOB = <Type.MEDIUMBLOB: 'MEDIUMBLOB'>
LONGBLOB = <Type.LONGBLOB: 'LONGBLOB'>
BINARY = <Type.BINARY: 'BINARY'>
VARBINARY = <Type.VARBINARY: 'VARBINARY'>
INT = <Type.INT: 'INT'>
UINT = <Type.UINT: 'UINT'>
TINYINT = <Type.TINYINT: 'TINYINT'>
UTINYINT = <Type.UTINYINT: 'UTINYINT'>
SMALLINT = <Type.SMALLINT: 'SMALLINT'>
USMALLINT = <Type.USMALLINT: 'USMALLINT'>
BIGINT = <Type.BIGINT: 'BIGINT'>
UBIGINT = <Type.UBIGINT: 'UBIGINT'>
FLOAT = <Type.FLOAT: 'FLOAT'>
DOUBLE = <Type.DOUBLE: 'DOUBLE'>
DECIMAL = <Type.DECIMAL: 'DECIMAL'>
BIGDECIMAL = <Type.BIGDECIMAL: 'BIGDECIMAL'>
BIT = <Type.BIT: 'BIT'>
BOOLEAN = <Type.BOOLEAN: 'BOOLEAN'>
JSON = <Type.JSON: 'JSON'>
JSONB = <Type.JSONB: 'JSONB'>
INTERVAL = <Type.INTERVAL: 'INTERVAL'>
TIME = <Type.TIME: 'TIME'>
TIMESTAMP = <Type.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPTZ = <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMPLTZ = <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
DATE = <Type.DATE: 'DATE'>
DATETIME = <Type.DATETIME: 'DATETIME'>
ARRAY = <Type.ARRAY: 'ARRAY'>
MAP = <Type.MAP: 'MAP'>
UUID = <Type.UUID: 'UUID'>
GEOGRAPHY = <Type.GEOGRAPHY: 'GEOGRAPHY'>
GEOMETRY = <Type.GEOMETRY: 'GEOMETRY'>
STRUCT = <Type.STRUCT: 'STRUCT'>
NULLABLE = <Type.NULLABLE: 'NULLABLE'>
HLLSKETCH = <Type.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <Type.HSTORE: 'HSTORE'>
SUPER = <Type.SUPER: 'SUPER'>
SERIAL = <Type.SERIAL: 'SERIAL'>
SMALLSERIAL = <Type.SMALLSERIAL: 'SMALLSERIAL'>
BIGSERIAL = <Type.BIGSERIAL: 'BIGSERIAL'>
XML = <Type.XML: 'XML'>
UNIQUEIDENTIFIER = <Type.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
MONEY = <Type.MONEY: 'MONEY'>
SMALLMONEY = <Type.SMALLMONEY: 'SMALLMONEY'>
ROWVERSION = <Type.ROWVERSION: 'ROWVERSION'>
IMAGE = <Type.IMAGE: 'IMAGE'>
VARIANT = <Type.VARIANT: 'VARIANT'>
OBJECT = <Type.OBJECT: 'OBJECT'>
INET = <Type.INET: 'INET'>
NULL = <Type.NULL: 'NULL'>
UNKNOWN = <Type.UNKNOWN: 'UNKNOWN'>
Inherited Members
enum.Enum
name
value
class PseudoType(Expression):
2943class PseudoType(Expression):
2944    pass
class StructKwarg(Expression):
2947class StructKwarg(Expression):
2948    arg_types = {"this": True, "expression": True}
class SubqueryPredicate(Predicate):
2952class SubqueryPredicate(Predicate):
2953    pass
class All(SubqueryPredicate):
2956class All(SubqueryPredicate):
2957    pass
class Any(SubqueryPredicate):
2960class Any(SubqueryPredicate):
2961    pass
class Exists(SubqueryPredicate):
2964class Exists(SubqueryPredicate):
2965    pass
class Command(Expression):
2970class Command(Expression):
2971    arg_types = {"this": True, "expression": False}
class Transaction(Expression):
2974class Transaction(Expression):
2975    arg_types = {"this": False, "modes": False}
class Commit(Expression):
2978class Commit(Expression):
2979    arg_types = {"chain": False}
class Rollback(Expression):
2982class Rollback(Expression):
2983    arg_types = {"savepoint": False}
class AlterTable(Expression):
2986class AlterTable(Expression):
2987    arg_types = {"this": True, "actions": True, "exists": False}
class AddConstraint(Expression):
2990class AddConstraint(Expression):
2991    arg_types = {"this": False, "expression": False, "enforced": False}
class DropPartition(Expression):
2994class DropPartition(Expression):
2995    arg_types = {"expressions": True, "exists": False}
class Binary(Expression):
2999class Binary(Expression):
3000    arg_types = {"this": True, "expression": True}
3001
3002    @property
3003    def left(self):
3004        return self.this
3005
3006    @property
3007    def right(self):
3008        return self.expression
class Add(Binary):
3011class Add(Binary):
3012    pass
class Connector(Binary, Condition):
3015class Connector(Binary, Condition):
3016    pass
class And(Connector):
3019class And(Connector):
3020    pass
class Or(Connector):
3023class Or(Connector):
3024    pass
class BitwiseAnd(Binary):
3027class BitwiseAnd(Binary):
3028    pass
class BitwiseLeftShift(Binary):
3031class BitwiseLeftShift(Binary):
3032    pass
class BitwiseOr(Binary):
3035class BitwiseOr(Binary):
3036    pass
class BitwiseRightShift(Binary):
3039class BitwiseRightShift(Binary):
3040    pass
class BitwiseXor(Binary):
3043class BitwiseXor(Binary):
3044    pass
class Div(Binary):
3047class Div(Binary):
3048    pass
class Overlaps(Binary):
3051class Overlaps(Binary):
3052    pass
class Dot(Binary):
3055class Dot(Binary):
3056    @property
3057    def name(self) -> str:
3058        return self.expression.name
3059
3060    @classmethod
3061    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3062        """Build a Dot object with a sequence of expressions."""
3063        if len(expressions) < 2:
3064            raise ValueError(f"Dot requires >= 2 expressions.")
3065
3066        a, b, *expressions = expressions
3067        dot = Dot(this=a, expression=b)
3068
3069        for expression in expressions:
3070            dot = Dot(this=dot, expression=expression)
3071
3072        return dot
@classmethod
def build( self, expressions: Sequence[sqlglot.expressions.Expression]) -> sqlglot.expressions.Dot:
3060    @classmethod
3061    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3062        """Build a Dot object with a sequence of expressions."""
3063        if len(expressions) < 2:
3064            raise ValueError(f"Dot requires >= 2 expressions.")
3065
3066        a, b, *expressions = expressions
3067        dot = Dot(this=a, expression=b)
3068
3069        for expression in expressions:
3070            dot = Dot(this=dot, expression=expression)
3071
3072        return dot

Build a Dot object with a sequence of expressions.

class DPipe(Binary):
3075class DPipe(Binary):
3076    pass
class EQ(Binary, Predicate):
3079class EQ(Binary, Predicate):
3080    pass
class NullSafeEQ(Binary, Predicate):
3083class NullSafeEQ(Binary, Predicate):
3084    pass
class NullSafeNEQ(Binary, Predicate):
3087class NullSafeNEQ(Binary, Predicate):
3088    pass
class Distance(Binary):
3091class Distance(Binary):
3092    pass
class Escape(Binary):
3095class Escape(Binary):
3096    pass
class Glob(Binary, Predicate):
3099class Glob(Binary, Predicate):
3100    pass
class GT(Binary, Predicate):
3103class GT(Binary, Predicate):
3104    pass
class GTE(Binary, Predicate):
3107class GTE(Binary, Predicate):
3108    pass
class ILike(Binary, Predicate):
3111class ILike(Binary, Predicate):
3112    pass
class ILikeAny(Binary, Predicate):
3115class ILikeAny(Binary, Predicate):
3116    pass
class IntDiv(Binary):
3119class IntDiv(Binary):
3120    pass
class Is(Binary, Predicate):
3123class Is(Binary, Predicate):
3124    pass
class Kwarg(Binary):
3127class Kwarg(Binary):
3128    """Kwarg in special functions like func(kwarg => y)."""

Kwarg in special functions like func(kwarg => y).

class Like(Binary, Predicate):
3131class Like(Binary, Predicate):
3132    pass
class LikeAny(Binary, Predicate):
3135class LikeAny(Binary, Predicate):
3136    pass
class LT(Binary, Predicate):
3139class LT(Binary, Predicate):
3140    pass
class LTE(Binary, Predicate):
3143class LTE(Binary, Predicate):
3144    pass
class Mod(Binary):
3147class Mod(Binary):
3148    pass
class Mul(Binary):
3151class Mul(Binary):
3152    pass
class NEQ(Binary, Predicate):
3155class NEQ(Binary, Predicate):
3156    pass
class SimilarTo(Binary, Predicate):
3159class SimilarTo(Binary, Predicate):
3160    pass
class Slice(Binary):
3163class Slice(Binary):
3164    arg_types = {"this": False, "expression": False}
class Sub(Binary):
3167class Sub(Binary):
3168    pass
class ArrayOverlaps(Binary):
3171class ArrayOverlaps(Binary):
3172    pass
class Unary(Expression):
3177class Unary(Expression):
3178    pass
class BitwiseNot(Unary):
3181class BitwiseNot(Unary):
3182    pass
class Not(Unary, Condition):
3185class Not(Unary, Condition):
3186    pass
class Paren(Unary, Condition):
3189class Paren(Unary, Condition):
3190    arg_types = {"this": True, "with": False}
class Neg(Unary):
3193class Neg(Unary):
3194    pass
class Alias(Expression):
3197class Alias(Expression):
3198    arg_types = {"this": True, "alias": False}
3199
3200    @property
3201    def output_name(self):
3202        return self.alias
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Aliases(Expression):
3205class Aliases(Expression):
3206    arg_types = {"this": True, "expressions": True}
3207
3208    @property
3209    def aliases(self):
3210        return self.expressions
class AtTimeZone(Expression):
3213class AtTimeZone(Expression):
3214    arg_types = {"this": True, "zone": True}
class Between(Predicate):
3217class Between(Predicate):
3218    arg_types = {"this": True, "low": True, "high": True}
class Bracket(Condition):
3221class Bracket(Condition):
3222    arg_types = {"this": True, "expressions": True}
class Distinct(Expression):
3225class Distinct(Expression):
3226    arg_types = {"expressions": False, "on": False}
class In(Predicate):
3229class In(Predicate):
3230    arg_types = {
3231        "this": True,
3232        "expressions": False,
3233        "query": False,
3234        "unnest": False,
3235        "field": False,
3236        "is_global": False,
3237    }
class TimeUnit(Expression):
3240class TimeUnit(Expression):
3241    """Automatically converts unit arg into a var."""
3242
3243    arg_types = {"unit": False}
3244
3245    def __init__(self, **args):
3246        unit = args.get("unit")
3247        if isinstance(unit, (Column, Literal)):
3248            args["unit"] = Var(this=unit.name)
3249        elif isinstance(unit, Week):
3250            unit.set("this", Var(this=unit.this.name))
3251        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3245    def __init__(self, **args):
3246        unit = args.get("unit")
3247        if isinstance(unit, (Column, Literal)):
3248            args["unit"] = Var(this=unit.name)
3249        elif isinstance(unit, Week):
3250            unit.set("this", Var(this=unit.this.name))
3251        super().__init__(**args)
class Interval(TimeUnit):
3254class Interval(TimeUnit):
3255    arg_types = {"this": False, "unit": False}
class IgnoreNulls(Expression):
3258class IgnoreNulls(Expression):
3259    pass
class RespectNulls(Expression):
3262class RespectNulls(Expression):
3263    pass
class Func(Condition):
3267class Func(Condition):
3268    """
3269    The base class for all function expressions.
3270
3271    Attributes:
3272        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3273            treated as a variable length argument and the argument's value will be stored as a list.
3274        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3275            for this function expression. These values are used to map this node to a name during parsing
3276            as well as to provide the function's name during SQL string generation. By default the SQL
3277            name is set to the expression's class name transformed to snake case.
3278    """
3279
3280    is_var_len_args = False
3281
3282    @classmethod
3283    def from_arg_list(cls, args):
3284        if cls.is_var_len_args:
3285            all_arg_keys = list(cls.arg_types)
3286            # If this function supports variable length argument treat the last argument as such.
3287            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3288            num_non_var = len(non_var_len_arg_keys)
3289
3290            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3291            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3292        else:
3293            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3294
3295        return cls(**args_dict)
3296
3297    @classmethod
3298    def sql_names(cls):
3299        if cls is Func:
3300            raise NotImplementedError(
3301                "SQL name is only supported by concrete function implementations"
3302            )
3303        if "_sql_names" not in cls.__dict__:
3304            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3305        return cls._sql_names
3306
3307    @classmethod
3308    def sql_name(cls):
3309        return cls.sql_names()[0]
3310
3311    @classmethod
3312    def default_parser_mappings(cls):
3313        return {name: cls.from_arg_list for name in cls.sql_names()}

The base class for all function expressions.

Attributes:
  • is_var_len_args (bool): if set to True the last argument defined in arg_types will be treated as a variable length argument and the argument's value will be stored as a list.
  • _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) for this function expression. These values are used to map this node to a name during parsing as well as to provide the function's name during SQL string generation. By default the SQL name is set to the expression's class name transformed to snake case.
@classmethod
def from_arg_list(cls, args):
3282    @classmethod
3283    def from_arg_list(cls, args):
3284        if cls.is_var_len_args:
3285            all_arg_keys = list(cls.arg_types)
3286            # If this function supports variable length argument treat the last argument as such.
3287            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3288            num_non_var = len(non_var_len_arg_keys)
3289
3290            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3291            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3292        else:
3293            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3294
3295        return cls(**args_dict)
@classmethod
def sql_names(cls):
3297    @classmethod
3298    def sql_names(cls):
3299        if cls is Func:
3300            raise NotImplementedError(
3301                "SQL name is only supported by concrete function implementations"
3302            )
3303        if "_sql_names" not in cls.__dict__:
3304            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3305        return cls._sql_names
@classmethod
def sql_name(cls):
3307    @classmethod
3308    def sql_name(cls):
3309        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3311    @classmethod
3312    def default_parser_mappings(cls):
3313        return {name: cls.from_arg_list for name in cls.sql_names()}
class AggFunc(Func):
3316class AggFunc(Func):
3317    pass
class Abs(Func):
3320class Abs(Func):
3321    pass
class Anonymous(Func):
3324class Anonymous(Func):
3325    arg_types = {"this": True, "expressions": False}
3326    is_var_len_args = True
class Hll(AggFunc):
3331class Hll(AggFunc):
3332    arg_types = {"this": True, "expressions": False}
3333    is_var_len_args = True
class ApproxDistinct(AggFunc):
3336class ApproxDistinct(AggFunc):
3337    arg_types = {"this": True, "accuracy": False}
class Array(Func):
3340class Array(Func):
3341    arg_types = {"expressions": False}
3342    is_var_len_args = True
class ToChar(Func):
3346class ToChar(Func):
3347    arg_types = {"this": True, "format": False}
class GenerateSeries(Func):
3350class GenerateSeries(Func):
3351    arg_types = {"start": True, "end": True, "step": False}
class ArrayAgg(AggFunc):
3354class ArrayAgg(AggFunc):
3355    pass
class ArrayAll(Func):
3358class ArrayAll(Func):
3359    arg_types = {"this": True, "expression": True}
class ArrayAny(Func):
3362class ArrayAny(Func):
3363    arg_types = {"this": True, "expression": True}
class ArrayConcat(Func):
3366class ArrayConcat(Func):
3367    arg_types = {"this": True, "expressions": False}
3368    is_var_len_args = True
class ArrayContains(Binary, Func):
3371class ArrayContains(Binary, Func):
3372    pass
class ArrayContained(Binary):
3375class ArrayContained(Binary):
3376    pass
class ArrayFilter(Func):
3379class ArrayFilter(Func):
3380    arg_types = {"this": True, "expression": True}
3381    _sql_names = ["FILTER", "ARRAY_FILTER"]
class ArrayJoin(Func):
3384class ArrayJoin(Func):
3385    arg_types = {"this": True, "expression": True, "null": False}
class ArraySize(Func):
3388class ArraySize(Func):
3389    arg_types = {"this": True, "expression": False}
class ArraySort(Func):
3392class ArraySort(Func):
3393    arg_types = {"this": True, "expression": False}
class ArraySum(Func):
3396class ArraySum(Func):
3397    pass
class ArrayUnionAgg(AggFunc):
3400class ArrayUnionAgg(AggFunc):
3401    pass
class Avg(AggFunc):
3404class Avg(AggFunc):
3405    pass
class AnyValue(AggFunc):
3408class AnyValue(AggFunc):
3409    pass
class Case(Func):
3412class Case(Func):
3413    arg_types = {"this": False, "ifs": True, "default": False}
class Cast(Func):
3416class Cast(Func):
3417    arg_types = {"this": True, "to": True}
3418
3419    @property
3420    def name(self) -> str:
3421        return self.this.name
3422
3423    @property
3424    def to(self):
3425        return self.args["to"]
3426
3427    @property
3428    def output_name(self):
3429        return self.name
3430
3431    def is_type(self, dtype: DataType.Type) -> bool:
3432        return self.to.is_type(dtype)
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def is_type(self, dtype: sqlglot.expressions.DataType.Type) -> bool:
3431    def is_type(self, dtype: DataType.Type) -> bool:
3432        return self.to.is_type(dtype)
class Collate(Binary):
3435class Collate(Binary):
3436    pass
class TryCast(Cast):
3439class TryCast(Cast):
3440    pass
class Ceil(Func):
3443class Ceil(Func):
3444    arg_types = {"this": True, "decimals": False}
3445    _sql_names = ["CEIL", "CEILING"]
class Coalesce(Func):
3448class Coalesce(Func):
3449    arg_types = {"this": True, "expressions": False}
3450    is_var_len_args = True
class Concat(Func):
3453class Concat(Func):
3454    arg_types = {"expressions": True}
3455    is_var_len_args = True
class ConcatWs(Concat):
3458class ConcatWs(Concat):
3459    _sql_names = ["CONCAT_WS"]
class Count(AggFunc):
3462class Count(AggFunc):
3463    arg_types = {"this": False}
class CountIf(AggFunc):
3466class CountIf(AggFunc):
3467    pass
class CurrentDate(Func):
3470class CurrentDate(Func):
3471    arg_types = {"this": False}
class CurrentDatetime(Func):
3474class CurrentDatetime(Func):
3475    arg_types = {"this": False}
class CurrentTime(Func):
3478class CurrentTime(Func):
3479    arg_types = {"this": False}
class CurrentTimestamp(Func):
3482class CurrentTimestamp(Func):
3483    arg_types = {"this": False}
class CurrentUser(Func):
3486class CurrentUser(Func):
3487    arg_types = {"this": False}
class DateAdd(Func, TimeUnit):
3490class DateAdd(Func, TimeUnit):
3491    arg_types = {"this": True, "expression": True, "unit": False}
class DateSub(Func, TimeUnit):
3494class DateSub(Func, TimeUnit):
3495    arg_types = {"this": True, "expression": True, "unit": False}
class DateDiff(Func, TimeUnit):
3498class DateDiff(Func, TimeUnit):
3499    _sql_names = ["DATEDIFF", "DATE_DIFF"]
3500    arg_types = {"this": True, "expression": True, "unit": False}
class DateTrunc(Func):
3503class DateTrunc(Func):
3504    arg_types = {"unit": True, "this": True, "zone": False}
class DatetimeAdd(Func, TimeUnit):
3507class DatetimeAdd(Func, TimeUnit):
3508    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeSub(Func, TimeUnit):
3511class DatetimeSub(Func, TimeUnit):
3512    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeDiff(Func, TimeUnit):
3515class DatetimeDiff(Func, TimeUnit):
3516    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeTrunc(Func, TimeUnit):
3519class DatetimeTrunc(Func, TimeUnit):
3520    arg_types = {"this": True, "unit": True, "zone": False}
class DayOfWeek(Func):
3523class DayOfWeek(Func):
3524    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
class DayOfMonth(Func):
3527class DayOfMonth(Func):
3528    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
class DayOfYear(Func):
3531class DayOfYear(Func):
3532    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
class WeekOfYear(Func):
3535class WeekOfYear(Func):
3536    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
class LastDateOfMonth(Func):
3539class LastDateOfMonth(Func):
3540    pass
class Extract(Func):
3543class Extract(Func):
3544    arg_types = {"this": True, "expression": True}
class TimestampAdd(Func, TimeUnit):
3547class TimestampAdd(Func, TimeUnit):
3548    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampSub(Func, TimeUnit):
3551class TimestampSub(Func, TimeUnit):
3552    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampDiff(Func, TimeUnit):
3555class TimestampDiff(Func, TimeUnit):
3556    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampTrunc(Func, TimeUnit):
3559class TimestampTrunc(Func, TimeUnit):
3560    arg_types = {"this": True, "unit": True, "zone": False}
class TimeAdd(Func, TimeUnit):
3563class TimeAdd(Func, TimeUnit):
3564    arg_types = {"this": True, "expression": True, "unit": False}
class TimeSub(Func, TimeUnit):
3567class TimeSub(Func, TimeUnit):
3568    arg_types = {"this": True, "expression": True, "unit": False}
class TimeDiff(Func, TimeUnit):
3571class TimeDiff(Func, TimeUnit):
3572    arg_types = {"this": True, "expression": True, "unit": False}
class TimeTrunc(Func, TimeUnit):
3575class TimeTrunc(Func, TimeUnit):
3576    arg_types = {"this": True, "unit": True, "zone": False}
class DateFromParts(Func):
3579class DateFromParts(Func):
3580    _sql_names = ["DATEFROMPARTS"]
3581    arg_types = {"year": True, "month": True, "day": True}
class DateStrToDate(Func):
3584class DateStrToDate(Func):
3585    pass
class DateToDateStr(Func):
3588class DateToDateStr(Func):
3589    pass
class DateToDi(Func):
3592class DateToDi(Func):
3593    pass
class Day(Func):
3596class Day(Func):
3597    pass
class Decode(Func):
3600class Decode(Func):
3601    arg_types = {"this": True, "charset": True, "replace": False}
class DiToDate(Func):
3604class DiToDate(Func):
3605    pass
class Encode(Func):
3608class Encode(Func):
3609    arg_types = {"this": True, "charset": True}
class Exp(Func):
3612class Exp(Func):
3613    pass
class Explode(Func):
3616class Explode(Func):
3617    pass
class ExponentialTimeDecayedAvg(AggFunc):
3620class ExponentialTimeDecayedAvg(AggFunc):
3621    arg_types = {"this": True, "time": False, "decay": False}
class Floor(Func):
3624class Floor(Func):
3625    arg_types = {"this": True, "decimals": False}
class Greatest(Func):
3628class Greatest(Func):
3629    arg_types = {"this": True, "expressions": False}
3630    is_var_len_args = True
class GroupConcat(Func):
3633class GroupConcat(Func):
3634    arg_types = {"this": True, "separator": False}
class GroupUniqArray(AggFunc):
3637class GroupUniqArray(AggFunc):
3638    arg_types = {"this": True, "size": False}
class Hex(Func):
3641class Hex(Func):
3642    pass
class Histogram(AggFunc):
3645class Histogram(AggFunc):
3646    arg_types = {"this": True, "bins": False}
class If(Func):
3649class If(Func):
3650    arg_types = {"this": True, "true": True, "false": False}
class IfNull(Func):
3653class IfNull(Func):
3654    arg_types = {"this": True, "expression": False}
3655    _sql_names = ["IFNULL", "NVL"]
class Initcap(Func):
3658class Initcap(Func):
3659    pass
class JSONKeyValue(Expression):
3662class JSONKeyValue(Expression):
3663    arg_types = {"this": True, "expression": True}
class JSONObject(Func):
3666class JSONObject(Func):
3667    arg_types = {
3668        "expressions": False,
3669        "null_handling": False,
3670        "unique_keys": False,
3671        "return_type": False,
3672        "format_json": False,
3673        "encoding": False,
3674    }
class JSONBContains(Binary):
3677class JSONBContains(Binary):
3678    _sql_names = ["JSONB_CONTAINS"]
class JSONExtract(Binary, Func):
3681class JSONExtract(Binary, Func):
3682    _sql_names = ["JSON_EXTRACT"]
class JSONExtractScalar(JSONExtract):
3685class JSONExtractScalar(JSONExtract):
3686    _sql_names = ["JSON_EXTRACT_SCALAR"]
class JSONBExtract(JSONExtract):
3689class JSONBExtract(JSONExtract):
3690    _sql_names = ["JSONB_EXTRACT"]
class JSONBExtractScalar(JSONExtract):
3693class JSONBExtractScalar(JSONExtract):
3694    _sql_names = ["JSONB_EXTRACT_SCALAR"]
class JSONFormat(Func):
3697class JSONFormat(Func):
3698    arg_types = {"this": False, "options": False}
3699    _sql_names = ["JSON_FORMAT"]
class Least(Func):
3702class Least(Func):
3703    arg_types = {"expressions": False}
3704    is_var_len_args = True
class Length(Func):
3707class Length(Func):
3708    pass
class Levenshtein(Func):
3711class Levenshtein(Func):
3712    arg_types = {
3713        "this": True,
3714        "expression": False,
3715        "ins_cost": False,
3716        "del_cost": False,
3717        "sub_cost": False,
3718    }
class Ln(Func):
3721class Ln(Func):
3722    pass
class Log(Func):
3725class Log(Func):
3726    arg_types = {"this": True, "expression": False}
class Log2(Func):
3729class Log2(Func):
3730    pass
class Log10(Func):
3733class Log10(Func):
3734    pass
class LogicalOr(AggFunc):
3737class LogicalOr(AggFunc):
3738    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
class LogicalAnd(AggFunc):
3741class LogicalAnd(AggFunc):
3742    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
class Lower(Func):
3745class Lower(Func):
3746    _sql_names = ["LOWER", "LCASE"]
class Map(Func):
3749class Map(Func):
3750    arg_types = {"keys": False, "values": False}
class StarMap(Func):
3753class StarMap(Func):
3754    pass
class VarMap(Func):
3757class VarMap(Func):
3758    arg_types = {"keys": True, "values": True}
3759    is_var_len_args = True
class MatchAgainst(Func):
3763class MatchAgainst(Func):
3764    arg_types = {"this": True, "expressions": True, "modifier": False}
class Max(AggFunc):
3767class Max(AggFunc):
3768    arg_types = {"this": True, "expressions": False}
3769    is_var_len_args = True
class Min(AggFunc):
3772class Min(AggFunc):
3773    arg_types = {"this": True, "expressions": False}
3774    is_var_len_args = True
class Month(Func):
3777class Month(Func):
3778    pass
class Nvl2(Func):
3781class Nvl2(Func):
3782    arg_types = {"this": True, "true": True, "false": False}
class Posexplode(Func):
3785class Posexplode(Func):
3786    pass
class Pow(Binary, Func):
3789class Pow(Binary, Func):
3790    _sql_names = ["POWER", "POW"]
class PercentileCont(AggFunc):
3793class PercentileCont(AggFunc):
3794    pass
class PercentileDisc(AggFunc):
3797class PercentileDisc(AggFunc):
3798    pass
class Quantile(AggFunc):
3801class Quantile(AggFunc):
3802    arg_types = {"this": True, "quantile": True}
class Quantiles(AggFunc):
3807class Quantiles(AggFunc):
3808    arg_types = {"parameters": True, "expressions": True}
3809    is_var_len_args = True
class QuantileIf(AggFunc):
3812class QuantileIf(AggFunc):
3813    arg_types = {"parameters": True, "expressions": True}
class ApproxQuantile(Quantile):
3816class ApproxQuantile(Quantile):
3817    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
class RangeN(Func):
3820class RangeN(Func):
3821    arg_types = {"this": True, "expressions": True, "each": False}
class ReadCSV(Func):
3824class ReadCSV(Func):
3825    _sql_names = ["READ_CSV"]
3826    is_var_len_args = True
3827    arg_types = {"this": True, "expressions": False}
class Reduce(Func):
3830class Reduce(Func):
3831    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
class RegexpExtract(Func):
3834class RegexpExtract(Func):
3835    arg_types = {
3836        "this": True,
3837        "expression": True,
3838        "position": False,
3839        "occurrence": False,
3840        "group": False,
3841    }
class RegexpLike(Func):
3844class RegexpLike(Func):
3845    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpILike(Func):
3848class RegexpILike(Func):
3849    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpSplit(Func):
3854class RegexpSplit(Func):
3855    arg_types = {"this": True, "expression": True, "limit": False}
class Repeat(Func):
3858class Repeat(Func):
3859    arg_types = {"this": True, "times": True}
class Round(Func):
3862class Round(Func):
3863    arg_types = {"this": True, "decimals": False}
class RowNumber(Func):
3866class RowNumber(Func):
3867    arg_types: t.Dict[str, t.Any] = {}
class SafeDivide(Func):
3870class SafeDivide(Func):
3871    arg_types = {"this": True, "expression": True}
class SetAgg(AggFunc):
3874class SetAgg(AggFunc):
3875    pass
class SortArray(Func):
3878class SortArray(Func):
3879    arg_types = {"this": True, "asc": False}
class Split(Func):
3882class Split(Func):
3883    arg_types = {"this": True, "expression": True, "limit": False}
class Substring(Func):
3888class Substring(Func):
3889    arg_types = {"this": True, "start": False, "length": False}
class StrPosition(Func):
3892class StrPosition(Func):
3893    arg_types = {
3894        "this": True,
3895        "substr": True,
3896        "position": False,
3897        "instance": False,
3898    }
class StrToDate(Func):
3901class StrToDate(Func):
3902    arg_types = {"this": True, "format": True}
class StrToTime(Func):
3905class StrToTime(Func):
3906    arg_types = {"this": True, "format": True}
class StrToUnix(Func):
3911class StrToUnix(Func):
3912    arg_types = {"this": False, "format": False}
class NumberToStr(Func):
3915class NumberToStr(Func):
3916    arg_types = {"this": True, "format": True}
class Struct(Func):
3919class Struct(Func):
3920    arg_types = {"expressions": True}
3921    is_var_len_args = True
class StructExtract(Func):
3924class StructExtract(Func):
3925    arg_types = {"this": True, "expression": True}
class Sum(AggFunc):
3928class Sum(AggFunc):
3929    pass
class Sqrt(Func):
3932class Sqrt(Func):
3933    pass
class Stddev(AggFunc):
3936class Stddev(AggFunc):
3937    pass
class StddevPop(AggFunc):
3940class StddevPop(AggFunc):
3941    pass
class StddevSamp(AggFunc):
3944class StddevSamp(AggFunc):
3945    pass
class TimeToStr(Func):
3948class TimeToStr(Func):
3949    arg_types = {"this": True, "format": True}
class TimeToTimeStr(Func):
3952class TimeToTimeStr(Func):
3953    pass
class TimeToUnix(Func):
3956class TimeToUnix(Func):
3957    pass
class TimeStrToDate(Func):
3960class TimeStrToDate(Func):
3961    pass
class TimeStrToTime(Func):
3964class TimeStrToTime(Func):
3965    pass
class TimeStrToUnix(Func):
3968class TimeStrToUnix(Func):
3969    pass
class Trim(Func):
3972class Trim(Func):
3973    arg_types = {
3974        "this": True,
3975        "expression": False,
3976        "position": False,
3977        "collation": False,
3978    }
class TsOrDsAdd(Func, TimeUnit):
3981class TsOrDsAdd(Func, TimeUnit):
3982    arg_types = {"this": True, "expression": True, "unit": False}
class TsOrDsToDateStr(Func):
3985class TsOrDsToDateStr(Func):
3986    pass
class TsOrDsToDate(Func):
3989class TsOrDsToDate(Func):
3990    arg_types = {"this": True, "format": False}
class TsOrDiToDi(Func):
3993class TsOrDiToDi(Func):
3994    pass
class Unhex(Func):
3997class Unhex(Func):
3998    pass
class UnixToStr(Func):
4001class UnixToStr(Func):
4002    arg_types = {"this": True, "format": False}
class UnixToTime(Func):
4007class UnixToTime(Func):
4008    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4009
4010    SECONDS = Literal.string("seconds")
4011    MILLIS = Literal.string("millis")
4012    MICROS = Literal.string("micros")
class UnixToTimeStr(Func):
4015class UnixToTimeStr(Func):
4016    pass
class Upper(Func):
4019class Upper(Func):
4020    _sql_names = ["UPPER", "UCASE"]
class Variance(AggFunc):
4023class Variance(AggFunc):
4024    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
class VariancePop(AggFunc):
4027class VariancePop(AggFunc):
4028    _sql_names = ["VARIANCE_POP", "VAR_POP"]
class Week(Func):
4031class Week(Func):
4032    arg_types = {"this": True, "mode": False}
class XMLTable(Func):
4035class XMLTable(Func):
4036    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
class Year(Func):
4039class Year(Func):
4040    pass
class Use(Expression):
4043class Use(Expression):
4044    arg_types = {"this": True, "kind": False}
class Merge(Expression):
4047class Merge(Expression):
4048    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
class When(Func):
4051class When(Func):
4052    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
def maybe_parse( sql_or_expression: Union[str, sqlglot.expressions.Expression], *, into: Union[str, Type[sqlglot.expressions.Expression], Collection[Union[str, Type[sqlglot.expressions.Expression]]], NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, prefix: Optional[str] = None, copy: bool = False, **opts) -> sqlglot.expressions.Expression:
4089def maybe_parse(
4090    sql_or_expression: ExpOrStr,
4091    *,
4092    into: t.Optional[IntoType] = None,
4093    dialect: DialectType = None,
4094    prefix: t.Optional[str] = None,
4095    copy: bool = False,
4096    **opts,
4097) -> Expression:
4098    """Gracefully handle a possible string or expression.
4099
4100    Example:
4101        >>> maybe_parse("1")
4102        (LITERAL this: 1, is_string: False)
4103        >>> maybe_parse(to_identifier("x"))
4104        (IDENTIFIER this: x, quoted: False)
4105
4106    Args:
4107        sql_or_expression: the SQL code string or an expression
4108        into: the SQLGlot Expression to parse into
4109        dialect: the dialect used to parse the input expressions (in the case that an
4110            input expression is a SQL string).
4111        prefix: a string to prefix the sql with before it gets parsed
4112            (automatically includes a space)
4113        copy: whether or not to copy the expression.
4114        **opts: other options to use to parse the input expressions (again, in the case
4115            that an input expression is a SQL string).
4116
4117    Returns:
4118        Expression: the parsed or given expression.
4119    """
4120    if isinstance(sql_or_expression, Expression):
4121        if copy:
4122            return sql_or_expression.copy()
4123        return sql_or_expression
4124
4125    import sqlglot
4126
4127    sql = str(sql_or_expression)
4128    if prefix:
4129        sql = f"{prefix} {sql}"
4130    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)

Gracefully handle a possible string or expression.

Example:
>>> maybe_parse("1")
(LITERAL this: 1, is_string: False)
>>> maybe_parse(to_identifier("x"))
(IDENTIFIER this: x, quoted: False)
Arguments:
  • sql_or_expression: the SQL code string or an expression
  • into: the SQLGlot Expression to parse into
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • prefix: a string to prefix the sql with before it gets parsed (automatically includes a space)
  • copy: whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Expression: the parsed or given expression.

def union(left, right, distinct=True, dialect=None, **opts):
4276def union(left, right, distinct=True, dialect=None, **opts):
4277    """
4278    Initializes a syntax tree from one UNION expression.
4279
4280    Example:
4281        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4282        'SELECT * FROM foo UNION SELECT * FROM bla'
4283
4284    Args:
4285        left (str | Expression): the SQL code string corresponding to the left-hand side.
4286            If an `Expression` instance is passed, it will be used as-is.
4287        right (str | Expression): the SQL code string corresponding to the right-hand side.
4288            If an `Expression` instance is passed, it will be used as-is.
4289        distinct (bool): set the DISTINCT flag if and only if this is true.
4290        dialect (str): the dialect used to parse the input expression.
4291        opts (kwargs): other options to use to parse the input expressions.
4292    Returns:
4293        Union: the syntax tree for the UNION expression.
4294    """
4295    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4296    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4297
4298    return Union(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one UNION expression.

Example:
>>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • left (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Union: the syntax tree for the UNION expression.

def intersect(left, right, distinct=True, dialect=None, **opts):
4301def intersect(left, right, distinct=True, dialect=None, **opts):
4302    """
4303    Initializes a syntax tree from one INTERSECT expression.
4304
4305    Example:
4306        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4307        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4308
4309    Args:
4310        left (str | Expression): the SQL code string corresponding to the left-hand side.
4311            If an `Expression` instance is passed, it will be used as-is.
4312        right (str | Expression): the SQL code string corresponding to the right-hand side.
4313            If an `Expression` instance is passed, it will be used as-is.
4314        distinct (bool): set the DISTINCT flag if and only if this is true.
4315        dialect (str): the dialect used to parse the input expression.
4316        opts (kwargs): other options to use to parse the input expressions.
4317    Returns:
4318        Intersect: the syntax tree for the INTERSECT expression.
4319    """
4320    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4321    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4322
4323    return Intersect(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one INTERSECT expression.

Example:
>>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • left (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Intersect: the syntax tree for the INTERSECT expression.

def except_(left, right, distinct=True, dialect=None, **opts):
4326def except_(left, right, distinct=True, dialect=None, **opts):
4327    """
4328    Initializes a syntax tree from one EXCEPT expression.
4329
4330    Example:
4331        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4332        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4333
4334    Args:
4335        left (str | Expression): the SQL code string corresponding to the left-hand side.
4336            If an `Expression` instance is passed, it will be used as-is.
4337        right (str | Expression): the SQL code string corresponding to the right-hand side.
4338            If an `Expression` instance is passed, it will be used as-is.
4339        distinct (bool): set the DISTINCT flag if and only if this is true.
4340        dialect (str): the dialect used to parse the input expression.
4341        opts (kwargs): other options to use to parse the input expressions.
4342    Returns:
4343        Except: the syntax tree for the EXCEPT statement.
4344    """
4345    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4346    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4347
4348    return Except(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one EXCEPT expression.

Example:
>>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • left (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Except: the syntax tree for the EXCEPT statement.

def select( *expressions: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
4351def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4352    """
4353    Initializes a syntax tree from one or multiple SELECT expressions.
4354
4355    Example:
4356        >>> select("col1", "col2").from_("tbl").sql()
4357        'SELECT col1, col2 FROM tbl'
4358
4359    Args:
4360        *expressions: the SQL code string to parse as the expressions of a
4361            SELECT statement. If an Expression instance is passed, this is used as-is.
4362        dialect: the dialect used to parse the input expressions (in the case that an
4363            input expression is a SQL string).
4364        **opts: other options to use to parse the input expressions (again, in the case
4365            that an input expression is a SQL string).
4366
4367    Returns:
4368        Select: the syntax tree for the SELECT statement.
4369    """
4370    return Select().select(*expressions, dialect=dialect, **opts)

Initializes a syntax tree from one or multiple SELECT expressions.

Example:
>>> select("col1", "col2").from_("tbl").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expressions: the SQL code string to parse as the expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def from_(*expressions, dialect=None, **opts) -> sqlglot.expressions.Select:
4373def from_(*expressions, dialect=None, **opts) -> Select:
4374    """
4375    Initializes a syntax tree from a FROM expression.
4376
4377    Example:
4378        >>> from_("tbl").select("col1", "col2").sql()
4379        'SELECT col1, col2 FROM tbl'
4380
4381    Args:
4382        *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a
4383            SELECT statement. If an Expression instance is passed, this is used as-is.
4384        dialect (str): the dialect used to parse the input expression (in the case that the
4385            input expression is a SQL string).
4386        **opts: other options to use to parse the input expressions (again, in the case
4387            that the input expression is a SQL string).
4388
4389    Returns:
4390        Select: the syntax tree for the SELECT statement.
4391    """
4392    return Select().from_(*expressions, dialect=dialect, **opts)

Initializes a syntax tree from a FROM expression.

Example:
>>> from_("tbl").select("col1", "col2").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def update( table: str | sqlglot.expressions.Table, properties: dict, where: Union[str, sqlglot.expressions.Expression, NoneType] = None, from_: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Update:
4395def update(
4396    table: str | Table,
4397    properties: dict,
4398    where: t.Optional[ExpOrStr] = None,
4399    from_: t.Optional[ExpOrStr] = None,
4400    dialect: DialectType = None,
4401    **opts,
4402) -> Update:
4403    """
4404    Creates an update statement.
4405
4406    Example:
4407        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
4408        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
4409
4410    Args:
4411        *properties: dictionary of properties to set which are
4412            auto converted to sql objects eg None -> NULL
4413        where: sql conditional parsed into a WHERE statement
4414        from_: sql statement parsed into a FROM statement
4415        dialect: the dialect used to parse the input expressions.
4416        **opts: other options to use to parse the input expressions.
4417
4418    Returns:
4419        Update: the syntax tree for the UPDATE statement.
4420    """
4421    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
4422    update_expr.set(
4423        "expressions",
4424        [
4425            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
4426            for k, v in properties.items()
4427        ],
4428    )
4429    if from_:
4430        update_expr.set(
4431            "from",
4432            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
4433        )
4434    if isinstance(where, Condition):
4435        where = Where(this=where)
4436    if where:
4437        update_expr.set(
4438            "where",
4439            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
4440        )
4441    return update_expr

Creates an update statement.

Example:
>>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
"UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
Arguments:
  • *properties: dictionary of properties to set which are auto converted to sql objects eg None -> NULL
  • where: sql conditional parsed into a WHERE statement
  • from_: sql statement parsed into a FROM statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Update: the syntax tree for the UPDATE statement.

def delete( table: Union[str, sqlglot.expressions.Expression], where: Union[str, sqlglot.expressions.Expression, NoneType] = None, returning: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Delete:
4444def delete(
4445    table: ExpOrStr,
4446    where: t.Optional[ExpOrStr] = None,
4447    returning: t.Optional[ExpOrStr] = None,
4448    dialect: DialectType = None,
4449    **opts,
4450) -> Delete:
4451    """
4452    Builds a delete statement.
4453
4454    Example:
4455        >>> delete("my_table", where="id > 1").sql()
4456        'DELETE FROM my_table WHERE id > 1'
4457
4458    Args:
4459        where: sql conditional parsed into a WHERE statement
4460        returning: sql conditional parsed into a RETURNING statement
4461        dialect: the dialect used to parse the input expressions.
4462        **opts: other options to use to parse the input expressions.
4463
4464    Returns:
4465        Delete: the syntax tree for the DELETE statement.
4466    """
4467    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
4468    if where:
4469        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
4470    if returning:
4471        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
4472    return delete_expr

Builds a delete statement.

Example:
>>> delete("my_table", where="id > 1").sql()
'DELETE FROM my_table WHERE id > 1'
Arguments:
  • where: sql conditional parsed into a WHERE statement
  • returning: sql conditional parsed into a RETURNING statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Delete: the syntax tree for the DELETE statement.

def condition(expression, dialect=None, **opts) -> sqlglot.expressions.Condition:
4475def condition(expression, dialect=None, **opts) -> Condition:
4476    """
4477    Initialize a logical condition expression.
4478
4479    Example:
4480        >>> condition("x=1").sql()
4481        'x = 1'
4482
4483        This is helpful for composing larger logical syntax trees:
4484        >>> where = condition("x=1")
4485        >>> where = where.and_("y=1")
4486        >>> Select().from_("tbl").select("*").where(where).sql()
4487        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
4488
4489    Args:
4490        *expression (str | Expression): the SQL code string to parse.
4491            If an Expression instance is passed, this is used as-is.
4492        dialect (str): the dialect used to parse the input expression (in the case that the
4493            input expression is a SQL string).
4494        **opts: other options to use to parse the input expressions (again, in the case
4495            that the input expression is a SQL string).
4496
4497    Returns:
4498        Condition: the expression
4499    """
4500    return maybe_parse(  # type: ignore
4501        expression,
4502        into=Condition,
4503        dialect=dialect,
4504        **opts,
4505    )

Initialize a logical condition expression.

Example:
>>> condition("x=1").sql()
'x = 1'

This is helpful for composing larger logical syntax trees:

>>> where = condition("x=1")
>>> where = where.and_("y=1")
>>> Select().from_("tbl").select("*").where(where).sql()
'SELECT * FROM tbl WHERE x = 1 AND y = 1'
Arguments:
  • *expression (str | Expression): the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

Condition: the expression

def and_(*expressions, dialect=None, **opts) -> sqlglot.expressions.And:
4508def and_(*expressions, dialect=None, **opts) -> And:
4509    """
4510    Combine multiple conditions with an AND logical operator.
4511
4512    Example:
4513        >>> and_("x=1", and_("y=1", "z=1")).sql()
4514        'x = 1 AND (y = 1 AND z = 1)'
4515
4516    Args:
4517        *expressions (str | Expression): the SQL code strings to parse.
4518            If an Expression instance is passed, this is used as-is.
4519        dialect (str): the dialect used to parse the input expression.
4520        **opts: other options to use to parse the input expressions.
4521
4522    Returns:
4523        And: the new condition
4524    """
4525    return _combine(expressions, And, dialect, **opts)

Combine multiple conditions with an AND logical operator.

Example:
>>> and_("x=1", and_("y=1", "z=1")).sql()
'x = 1 AND (y = 1 AND z = 1)'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

And: the new condition

def or_(*expressions, dialect=None, **opts) -> sqlglot.expressions.Or:
4528def or_(*expressions, dialect=None, **opts) -> Or:
4529    """
4530    Combine multiple conditions with an OR logical operator.
4531
4532    Example:
4533        >>> or_("x=1", or_("y=1", "z=1")).sql()
4534        'x = 1 OR (y = 1 OR z = 1)'
4535
4536    Args:
4537        *expressions (str | Expression): the SQL code strings to parse.
4538            If an Expression instance is passed, this is used as-is.
4539        dialect (str): the dialect used to parse the input expression.
4540        **opts: other options to use to parse the input expressions.
4541
4542    Returns:
4543        Or: the new condition
4544    """
4545    return _combine(expressions, Or, dialect, **opts)

Combine multiple conditions with an OR logical operator.

Example:
>>> or_("x=1", or_("y=1", "z=1")).sql()
'x = 1 OR (y = 1 OR z = 1)'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Or: the new condition

def not_(expression, dialect=None, **opts) -> sqlglot.expressions.Not:
4548def not_(expression, dialect=None, **opts) -> Not:
4549    """
4550    Wrap a condition with a NOT operator.
4551
4552    Example:
4553        >>> not_("this_suit='black'").sql()
4554        "NOT this_suit = 'black'"
4555
4556    Args:
4557        expression (str | Expression): the SQL code strings to parse.
4558            If an Expression instance is passed, this is used as-is.
4559        dialect (str): the dialect used to parse the input expression.
4560        **opts: other options to use to parse the input expressions.
4561
4562    Returns:
4563        Not: the new condition
4564    """
4565    this = condition(
4566        expression,
4567        dialect=dialect,
4568        **opts,
4569    )
4570    return Not(this=_wrap_operator(this))

Wrap a condition with a NOT operator.

Example:
>>> not_("this_suit='black'").sql()
"NOT this_suit = 'black'"
Arguments:
  • expression (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Not: the new condition

def paren(expression) -> sqlglot.expressions.Paren:
4573def paren(expression) -> Paren:
4574    return Paren(this=expression)
def to_identifier(name, quoted=None):
4590def to_identifier(name, quoted=None):
4591    """Builds an identifier.
4592
4593    Args:
4594        name: The name to turn into an identifier.
4595        quoted: Whether or not force quote the identifier.
4596
4597    Returns:
4598        The identifier ast node.
4599    """
4600
4601    if name is None:
4602        return None
4603
4604    if isinstance(name, Identifier):
4605        identifier = name
4606    elif isinstance(name, str):
4607        identifier = Identifier(
4608            this=name,
4609            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
4610        )
4611    else:
4612        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
4613    return identifier

Builds an identifier.

Arguments:
  • name: The name to turn into an identifier.
  • quoted: Whether or not force quote the identifier.
Returns:

The identifier ast node.

def to_interval( interval: str | sqlglot.expressions.Literal) -> sqlglot.expressions.Interval:
4619def to_interval(interval: str | Literal) -> Interval:
4620    """Builds an interval expression from a string like '1 day' or '5 months'."""
4621    if isinstance(interval, Literal):
4622        if not interval.is_string:
4623            raise ValueError("Invalid interval string.")
4624
4625        interval = interval.this
4626
4627    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
4628
4629    if not interval_parts:
4630        raise ValueError("Invalid interval string.")
4631
4632    return Interval(
4633        this=Literal.string(interval_parts.group(1)),
4634        unit=Var(this=interval_parts.group(2)),
4635    )

Builds an interval expression from a string like '1 day' or '5 months'.

def to_table( sql_path: Union[str, sqlglot.expressions.Table, NoneType], **kwargs) -> Optional[sqlglot.expressions.Table]:
4648def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]:
4649    """
4650    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
4651    If a table is passed in then that table is returned.
4652
4653    Args:
4654        sql_path: a `[catalog].[schema].[table]` string.
4655
4656    Returns:
4657        A table expression.
4658    """
4659    if sql_path is None or isinstance(sql_path, Table):
4660        return sql_path
4661    if not isinstance(sql_path, str):
4662        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
4663
4664    catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3))
4665    return Table(this=table_name, db=db, catalog=catalog, **kwargs)

Create a table expression from a [catalog].[schema].[table] sql path. Catalog and schema are optional. If a table is passed in then that table is returned.

Arguments:
  • sql_path: a [catalog].[schema].[table] string.
Returns:

A table expression.

def to_column( sql_path: str | sqlglot.expressions.Column, **kwargs) -> sqlglot.expressions.Column:
4668def to_column(sql_path: str | Column, **kwargs) -> Column:
4669    """
4670    Create a column from a `[table].[column]` sql path. Schema is optional.
4671
4672    If a column is passed in then that column is returned.
4673
4674    Args:
4675        sql_path: `[table].[column]` string
4676    Returns:
4677        Table: A column expression
4678    """
4679    if sql_path is None or isinstance(sql_path, Column):
4680        return sql_path
4681    if not isinstance(sql_path, str):
4682        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
4683    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore

Create a column from a [table].[column] sql path. Schema is optional.

If a column is passed in then that column is returned.

Arguments:
  • sql_path: [table].[column] string
Returns:

Table: A column expression

def alias_( expression: Union[str, sqlglot.expressions.Expression], alias: str | sqlglot.expressions.Identifier, table: Union[bool, Sequence[str | sqlglot.expressions.Identifier]] = False, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts):
4686def alias_(
4687    expression: ExpOrStr,
4688    alias: str | Identifier,
4689    table: bool | t.Sequence[str | Identifier] = False,
4690    quoted: t.Optional[bool] = None,
4691    dialect: DialectType = None,
4692    **opts,
4693):
4694    """Create an Alias expression.
4695
4696    Example:
4697        >>> alias_('foo', 'bar').sql()
4698        'foo AS bar'
4699
4700        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
4701        '(SELECT 1, 2) AS bar(a, b)'
4702
4703    Args:
4704        expression: the SQL code strings to parse.
4705            If an Expression instance is passed, this is used as-is.
4706        alias: the alias name to use. If the name has
4707            special characters it is quoted.
4708        table: Whether or not to create a table alias, can also be a list of columns.
4709        quoted: whether or not to quote the alias
4710        dialect: the dialect used to parse the input expression.
4711        **opts: other options to use to parse the input expressions.
4712
4713    Returns:
4714        Alias: the aliased expression
4715    """
4716    exp = maybe_parse(expression, dialect=dialect, **opts)
4717    alias = to_identifier(alias, quoted=quoted)
4718
4719    if table:
4720        table_alias = TableAlias(this=alias)
4721        exp.set("alias", table_alias)
4722
4723        if not isinstance(table, bool):
4724            for column in table:
4725                table_alias.append("columns", to_identifier(column, quoted=quoted))
4726
4727        return exp
4728
4729    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
4730    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
4731    # for the complete Window expression.
4732    #
4733    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
4734
4735    if "alias" in exp.arg_types and not isinstance(exp, Window):
4736        exp = exp.copy()
4737        exp.set("alias", alias)
4738        return exp
4739    return Alias(this=exp, alias=alias)

Create an Alias expression.

Example:
>>> alias_('foo', 'bar').sql()
'foo AS bar'
>>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
'(SELECT 1, 2) AS bar(a, b)'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias: the alias name to use. If the name has special characters it is quoted.
  • table: Whether or not to create a table alias, can also be a list of columns.
  • quoted: whether or not to quote the alias
  • dialect: the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Alias: the aliased expression

def subquery(expression, alias=None, dialect=None, **opts):
4742def subquery(expression, alias=None, dialect=None, **opts):
4743    """
4744    Build a subquery expression.
4745
4746    Example:
4747        >>> subquery('select x from tbl', 'bar').select('x').sql()
4748        'SELECT x FROM (SELECT x FROM tbl) AS bar'
4749
4750    Args:
4751        expression (str | Expression): the SQL code strings to parse.
4752            If an Expression instance is passed, this is used as-is.
4753        alias (str | Expression): the alias name to use.
4754        dialect (str): the dialect used to parse the input expression.
4755        **opts: other options to use to parse the input expressions.
4756
4757    Returns:
4758        Select: a new select with the subquery expression included
4759    """
4760
4761    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
4762    return Select().from_(expression, dialect=dialect, **opts)

Build a subquery expression.

Example:
>>> subquery('select x from tbl', 'bar').select('x').sql()
'SELECT x FROM (SELECT x FROM tbl) AS bar'
Arguments:
  • expression (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias (str | Expression): the alias name to use.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Select: a new select with the subquery expression included

def column( col: str | sqlglot.expressions.Identifier, table: Union[str, sqlglot.expressions.Identifier, NoneType] = None, db: Union[str, sqlglot.expressions.Identifier, NoneType] = None, catalog: Union[str, sqlglot.expressions.Identifier, NoneType] = None, quoted: Optional[bool] = None) -> sqlglot.expressions.Column:
4765def column(
4766    col: str | Identifier,
4767    table: t.Optional[str | Identifier] = None,
4768    db: t.Optional[str | Identifier] = None,
4769    catalog: t.Optional[str | Identifier] = None,
4770    quoted: t.Optional[bool] = None,
4771) -> Column:
4772    """
4773    Build a Column.
4774
4775    Args:
4776        col: column name
4777        table: table name
4778        db: db name
4779        catalog: catalog name
4780        quoted: whether or not to force quote each part
4781    Returns:
4782        Column: column instance
4783    """
4784    return Column(
4785        this=to_identifier(col, quoted=quoted),
4786        table=to_identifier(table, quoted=quoted),
4787        db=to_identifier(db, quoted=quoted),
4788        catalog=to_identifier(catalog, quoted=quoted),
4789    )

Build a Column.

Arguments:
  • col: column name
  • table: table name
  • db: db name
  • catalog: catalog name
  • quoted: whether or not to force quote each part
Returns:

Column: column instance

def cast( expression: Union[str, sqlglot.expressions.Expression], to: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, **opts) -> sqlglot.expressions.Cast:
4792def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
4793    """Cast an expression to a data type.
4794
4795    Example:
4796        >>> cast('x + 1', 'int').sql()
4797        'CAST(x + 1 AS INT)'
4798
4799    Args:
4800        expression: The expression to cast.
4801        to: The datatype to cast to.
4802
4803    Returns:
4804        A cast node.
4805    """
4806    expression = maybe_parse(expression, **opts)
4807    return Cast(this=expression, to=DataType.build(to, **opts))

Cast an expression to a data type.

Example:
>>> cast('x + 1', 'int').sql()
'CAST(x + 1 AS INT)'
Arguments:
  • expression: The expression to cast.
  • to: The datatype to cast to.
Returns:

A cast node.

def table_( table, db=None, catalog=None, quoted=None, alias=None) -> sqlglot.expressions.Table:
4810def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table:
4811    """Build a Table.
4812
4813    Args:
4814        table (str | Expression): column name
4815        db (str | Expression): db name
4816        catalog (str | Expression): catalog name
4817
4818    Returns:
4819        Table: table instance
4820    """
4821    return Table(
4822        this=to_identifier(table, quoted=quoted),
4823        db=to_identifier(db, quoted=quoted),
4824        catalog=to_identifier(catalog, quoted=quoted),
4825        alias=TableAlias(this=to_identifier(alias)) if alias else None,
4826    )

Build a Table.

Arguments:
  • table (str | Expression): column name
  • db (str | Expression): db name
  • catalog (str | Expression): catalog name
Returns:

Table: table instance

def values( values: Iterable[Tuple[Any, ...]], alias: Optional[str] = None, columns: Union[Iterable[str], Dict[str, sqlglot.expressions.DataType], NoneType] = None) -> sqlglot.expressions.Values:
4829def values(
4830    values: t.Iterable[t.Tuple[t.Any, ...]],
4831    alias: t.Optional[str] = None,
4832    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
4833) -> Values:
4834    """Build VALUES statement.
4835
4836    Example:
4837        >>> values([(1, '2')]).sql()
4838        "VALUES (1, '2')"
4839
4840    Args:
4841        values: values statements that will be converted to SQL
4842        alias: optional alias
4843        columns: Optional list of ordered column names or ordered dictionary of column names to types.
4844         If either are provided then an alias is also required.
4845         If a dictionary is provided then the first column of the values will be casted to the expected type
4846         in order to help with type inference.
4847
4848    Returns:
4849        Values: the Values expression object
4850    """
4851    if columns and not alias:
4852        raise ValueError("Alias is required when providing columns")
4853    table_alias = (
4854        TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
4855        if columns
4856        else TableAlias(this=to_identifier(alias) if alias else None)
4857    )
4858    expressions = [convert(tup) for tup in values]
4859    if columns and isinstance(columns, dict):
4860        types = list(columns.values())
4861        expressions[0].set(
4862            "expressions",
4863            [cast(x, types[i]) for i, x in enumerate(expressions[0].expressions)],
4864        )
4865    return Values(
4866        expressions=expressions,
4867        alias=table_alias,
4868    )

Build VALUES statement.

Example:
>>> values([(1, '2')]).sql()
"VALUES (1, '2')"
Arguments:
  • values: values statements that will be converted to SQL
  • alias: optional alias
  • columns: Optional list of ordered column names or ordered dictionary of column names to types. If either are provided then an alias is also required. If a dictionary is provided then the first column of the values will be casted to the expected type in order to help with type inference.
Returns:

Values: the Values expression object

def var( name: Union[str, sqlglot.expressions.Expression, NoneType]) -> sqlglot.expressions.Var:
4871def var(name: t.Optional[ExpOrStr]) -> Var:
4872    """Build a SQL variable.
4873
4874    Example:
4875        >>> repr(var('x'))
4876        '(VAR this: x)'
4877
4878        >>> repr(var(column('x', table='y')))
4879        '(VAR this: x)'
4880
4881    Args:
4882        name: The name of the var or an expression who's name will become the var.
4883
4884    Returns:
4885        The new variable node.
4886    """
4887    if not name:
4888        raise ValueError("Cannot convert empty name into var.")
4889
4890    if isinstance(name, Expression):
4891        name = name.name
4892    return Var(this=name)

Build a SQL variable.

Example:
>>> repr(var('x'))
'(VAR this: x)'
>>> repr(var(column('x', table='y')))
'(VAR this: x)'
Arguments:
  • name: The name of the var or an expression who's name will become the var.
Returns:

The new variable node.

def rename_table( old_name: str | sqlglot.expressions.Table, new_name: str | sqlglot.expressions.Table) -> sqlglot.expressions.AlterTable:
4895def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
4896    """Build ALTER TABLE... RENAME... expression
4897
4898    Args:
4899        old_name: The old name of the table
4900        new_name: The new name of the table
4901
4902    Returns:
4903        Alter table expression
4904    """
4905    old_table = to_table(old_name)
4906    new_table = to_table(new_name)
4907    return AlterTable(
4908        this=old_table,
4909        actions=[
4910            RenameTable(this=new_table),
4911        ],
4912    )

Build ALTER TABLE... RENAME... expression

Arguments:
  • old_name: The old name of the table
  • new_name: The new name of the table
Returns:

Alter table expression

def convert(value) -> sqlglot.expressions.Expression:
4915def convert(value) -> Expression:
4916    """Convert a python value into an expression object.
4917
4918    Raises an error if a conversion is not possible.
4919
4920    Args:
4921        value (Any): a python object
4922
4923    Returns:
4924        Expression: the equivalent expression object
4925    """
4926    if isinstance(value, Expression):
4927        return value
4928    if value is None:
4929        return NULL
4930    if isinstance(value, bool):
4931        return Boolean(this=value)
4932    if isinstance(value, str):
4933        return Literal.string(value)
4934    if isinstance(value, float) and math.isnan(value):
4935        return NULL
4936    if isinstance(value, numbers.Number):
4937        return Literal.number(value)
4938    if isinstance(value, tuple):
4939        return Tuple(expressions=[convert(v) for v in value])
4940    if isinstance(value, list):
4941        return Array(expressions=[convert(v) for v in value])
4942    if isinstance(value, dict):
4943        return Map(
4944            keys=[convert(k) for k in value],
4945            values=[convert(v) for v in value.values()],
4946        )
4947    if isinstance(value, datetime.datetime):
4948        datetime_literal = Literal.string(
4949            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
4950        )
4951        return TimeStrToTime(this=datetime_literal)
4952    if isinstance(value, datetime.date):
4953        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
4954        return DateStrToDate(this=date_literal)
4955    raise ValueError(f"Cannot convert {value}")

Convert a python value into an expression object.

Raises an error if a conversion is not possible.

Arguments:
  • value (Any): a python object
Returns:

Expression: the equivalent expression object

def replace_children(expression, fun, *args, **kwargs):
4958def replace_children(expression, fun, *args, **kwargs):
4959    """
4960    Replace children of an expression with the result of a lambda fun(child) -> exp.
4961    """
4962    for k, v in expression.args.items():
4963        is_list_arg = type(v) is list
4964
4965        child_nodes = v if is_list_arg else [v]
4966        new_child_nodes = []
4967
4968        for cn in child_nodes:
4969            if isinstance(cn, Expression):
4970                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
4971                    new_child_nodes.append(child_node)
4972                    child_node.parent = expression
4973                    child_node.arg_key = k
4974            else:
4975                new_child_nodes.append(cn)
4976
4977        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)

Replace children of an expression with the result of a lambda fun(child) -> exp.

def column_table_names(expression):
4980def column_table_names(expression):
4981    """
4982    Return all table names referenced through columns in an expression.
4983
4984    Example:
4985        >>> import sqlglot
4986        >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
4987        ['c', 'a']
4988
4989    Args:
4990        expression (sqlglot.Expression): expression to find table names
4991
4992    Returns:
4993        list: A list of unique names
4994    """
4995    return list(dict.fromkeys(column.table for column in expression.find_all(Column)))

Return all table names referenced through columns in an expression.

Example:
>>> import sqlglot
>>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
['c', 'a']
Arguments:
  • expression (sqlglot.Expression): expression to find table names
Returns:

list: A list of unique names

def table_name(table) -> str:
4998def table_name(table) -> str:
4999    """Get the full name of a table as a string.
5000
5001    Args:
5002        table (exp.Table | str): table expression node or string.
5003
5004    Examples:
5005        >>> from sqlglot import exp, parse_one
5006        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5007        'a.b.c'
5008
5009    Returns:
5010        The table name.
5011    """
5012
5013    table = maybe_parse(table, into=Table)
5014
5015    if not table:
5016        raise ValueError(f"Cannot parse {table}")
5017
5018    return ".".join(
5019        part
5020        for part in (
5021            table.text("catalog"),
5022            table.text("db"),
5023            table.name,
5024        )
5025        if part
5026    )

Get the full name of a table as a string.

Arguments:
  • table (exp.Table | str): table expression node or string.
Examples:
>>> from sqlglot import exp, parse_one
>>> table_name(parse_one("select * from a.b.c").find(exp.Table))
'a.b.c'
Returns:

The table name.

def replace_tables(expression, mapping):
5029def replace_tables(expression, mapping):
5030    """Replace all tables in expression according to the mapping.
5031
5032    Args:
5033        expression (sqlglot.Expression): expression node to be transformed and replaced.
5034        mapping (Dict[str, str]): mapping of table names.
5035
5036    Examples:
5037        >>> from sqlglot import exp, parse_one
5038        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5039        'SELECT * FROM c'
5040
5041    Returns:
5042        The mapped expression.
5043    """
5044
5045    def _replace_tables(node):
5046        if isinstance(node, Table):
5047            new_name = mapping.get(table_name(node))
5048            if new_name:
5049                return to_table(
5050                    new_name,
5051                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5052                )
5053        return node
5054
5055    return expression.transform(_replace_tables)

Replace all tables in expression according to the mapping.

Arguments:
  • expression (sqlglot.Expression): expression node to be transformed and replaced.
  • mapping (Dict[str, str]): mapping of table names.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
'SELECT * FROM c'
Returns:

The mapped expression.

def replace_placeholders(expression, *args, **kwargs):
5058def replace_placeholders(expression, *args, **kwargs):
5059    """Replace placeholders in an expression.
5060
5061    Args:
5062        expression (sqlglot.Expression): expression node to be transformed and replaced.
5063        args: positional names that will substitute unnamed placeholders in the given order.
5064        kwargs: keyword arguments that will substitute named placeholders.
5065
5066    Examples:
5067        >>> from sqlglot import exp, parse_one
5068        >>> replace_placeholders(
5069        ...     parse_one("select * from :tbl where ? = ?"),
5070        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5071        ... ).sql()
5072        "SELECT * FROM foo WHERE str_col = 'b'"
5073
5074    Returns:
5075        The mapped expression.
5076    """
5077
5078    def _replace_placeholders(node, args, **kwargs):
5079        if isinstance(node, Placeholder):
5080            if node.name:
5081                new_name = kwargs.get(node.name)
5082                if new_name:
5083                    return convert(new_name)
5084            else:
5085                try:
5086                    return convert(next(args))
5087                except StopIteration:
5088                    pass
5089        return node
5090
5091    return expression.transform(_replace_placeholders, iter(args), **kwargs)

Replace placeholders in an expression.

Arguments:
  • expression (sqlglot.Expression): expression node to be transformed and replaced.
  • args: positional names that will substitute unnamed placeholders in the given order.
  • kwargs: keyword arguments that will substitute named placeholders.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_placeholders(
...     parse_one("select * from :tbl where ? = ?"),
...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
... ).sql()
"SELECT * FROM foo WHERE str_col = 'b'"
Returns:

The mapped expression.

def expand( expression: sqlglot.expressions.Expression, sources: Dict[str, sqlglot.expressions.Subqueryable], copy: bool = True) -> sqlglot.expressions.Expression:
5094def expand(
5095    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5096) -> Expression:
5097    """Transforms an expression by expanding all referenced sources into subqueries.
5098
5099    Examples:
5100        >>> from sqlglot import parse_one
5101        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5102        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5103
5104        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5105        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5106
5107    Args:
5108        expression: The expression to expand.
5109        sources: A dictionary of name to Subqueryables.
5110        copy: Whether or not to copy the expression during transformation. Defaults to True.
5111
5112    Returns:
5113        The transformed expression.
5114    """
5115
5116    def _expand(node: Expression):
5117        if isinstance(node, Table):
5118            name = table_name(node)
5119            source = sources.get(name)
5120            if source:
5121                subquery = source.subquery(node.alias or name)
5122                subquery.comments = [f"source: {name}"]
5123                return subquery.transform(_expand, copy=False)
5124        return node
5125
5126    return expression.transform(_expand, copy=copy)

Transforms an expression by expanding all referenced sources into subqueries.

Examples:
>>> from sqlglot import parse_one
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
Arguments:
  • expression: The expression to expand.
  • sources: A dictionary of name to Subqueryables.
  • copy: Whether or not to copy the expression during transformation. Defaults to True.
Returns:

The transformed expression.

def func( name: str, *args, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.Func:
5129def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5130    """
5131    Returns a Func expression.
5132
5133    Examples:
5134        >>> func("abs", 5).sql()
5135        'ABS(5)'
5136
5137        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5138        'CAST(5 AS DOUBLE)'
5139
5140    Args:
5141        name: the name of the function to build.
5142        args: the args used to instantiate the function of interest.
5143        dialect: the source dialect.
5144        kwargs: the kwargs used to instantiate the function of interest.
5145
5146    Note:
5147        The arguments `args` and `kwargs` are mutually exclusive.
5148
5149    Returns:
5150        An instance of the function of interest, or an anonymous function, if `name` doesn't
5151        correspond to an existing `sqlglot.expressions.Func` class.
5152    """
5153    if args and kwargs:
5154        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5155
5156    from sqlglot.dialects.dialect import Dialect
5157
5158    converted = [convert(arg) for arg in args]
5159    kwargs = {key: convert(value) for key, value in kwargs.items()}
5160
5161    parser = Dialect.get_or_raise(dialect)().parser()
5162    from_args_list = parser.FUNCTIONS.get(name.upper())
5163
5164    if from_args_list:
5165        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5166    else:
5167        kwargs = kwargs or {"expressions": converted}
5168        function = Anonymous(this=name, **kwargs)
5169
5170    for error_message in function.error_messages(converted):
5171        raise ValueError(error_message)
5172
5173    return function

Returns a Func expression.

Examples:
>>> func("abs", 5).sql()
'ABS(5)'
>>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
'CAST(5 AS DOUBLE)'
Arguments:
  • name: the name of the function to build.
  • args: the args used to instantiate the function of interest.
  • dialect: the source dialect.
  • kwargs: the kwargs used to instantiate the function of interest.
Note:

The arguments args and kwargs are mutually exclusive.

Returns:

An instance of the function of interest, or an anonymous function, if name doesn't correspond to an existing sqlglot.expressions.Func class.

def true():
5176def true():
5177    """
5178    Returns a true Boolean expression.
5179    """
5180    return Boolean(this=True)

Returns a true Boolean expression.

def false():
5183def false():
5184    """
5185    Returns a false Boolean expression.
5186    """
5187    return Boolean(this=False)

Returns a false Boolean expression.

def null():
5190def null():
5191    """
5192    Returns a Null expression.
5193    """
5194    return Null()

Returns a Null expression.